Skip to content

Commit

Permalink
dhcp client: allow trying once to get a lease then exiting, like dhcl…
Browse files Browse the repository at this point in the history
…ient -1
  • Loading branch information
etene committed Feb 1, 2025
1 parent 26cd5f7 commit 133c63f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 15 deletions.
33 changes: 19 additions & 14 deletions pyroute2/dhcp/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,11 @@ def get_psr() -> ArgumentParser:
)
psr.add_argument(
'-x',
'--exit-on-lease',
help='Exit as soon as getting a lease.',
default=False,
action='store_true',
'--exit-on-timeout',
metavar='N',
help='Wait for max N seconds for a lease, '
'exit if none could be obtained.',
type=int,
)
psr.add_argument(
'--log-level',
Expand Down Expand Up @@ -91,21 +92,25 @@ async def main():
# Open the socket, read existing lease, etc
async with AsyncDHCPClient(cfg) as acli:
# Bootstrap the client by sending a DISCOVER or a REQUEST
await acli.bootstrap()
if args.exit_on_lease:
# Wait until we're bound once, then exit
await acli.wait_for_state(State.BOUND)
else:
# Wait until the client is stopped otherwise
try:
await acli.bootstrap()
if args.exit_on_timeout:
# Wait a bit for a lease, and exit if we have none
try:
await acli.wait_for_state(
State.BOUND, timeout=args.exit_on_timeout
)
except TimeoutError as err:
psr.error(str(err))
# Wait until the client is stopped
await acli.wait_for_state(State.OFF)
except (asyncio.CancelledError, KeyboardInterrupt):
pass


def run():
# for the setup.cfg entrypoint
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
asyncio.run(main())


if __name__ == '__main__':
Expand Down
1 change: 1 addition & 0 deletions pyroute2/dhcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ async def _send_forever(self) -> None:
floor(time() - self.last_state_change), 0xFFFF
)
msg_to_send.dhcp['xid'] = self.xid.for_state(self.state)
# TODO: don't send aynthing else than RELEASEs when stopping
LOG.info('Sending %s', msg_to_send)
await self._sock.put(msg_to_send)

Expand Down
7 changes: 6 additions & 1 deletion tests/test_linux/test_dhcp/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import json
import signal
from ipaddress import IPv4Address

import pytest
Expand All @@ -18,10 +19,14 @@ async def test_client_console(dnsmasq: DnsmasqFixture, veth_pair: VethPair):
veth_pair.client,
'--lease-type',
'pyroute2.dhcp.leases.JSONStdoutLease',
'--exit-on-lease',
'--exit-on-timeout=5',
'--log-level=DEBUG',
stdout=asyncio.subprocess.PIPE,
)

asyncio.get_running_loop().call_later(
2, process.send_signal, signal.SIGINT
)
try:
stdout, _ = await asyncio.wait_for(process.communicate(), timeout=5)
except TimeoutError:
Expand Down

0 comments on commit 133c63f

Please sign in to comment.