From 972f796b4de76c46ac92868686c5339f313c0142 Mon Sep 17 00:00:00 2001 From: JDierkse Date: Tue, 24 Jan 2023 13:19:24 +0100 Subject: [PATCH] Store and restore static routes upon DHCP renew --- net-dhcp/network.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/net-dhcp/network.py b/net-dhcp/network.py index 9bc8627..dfe8607 100644 --- a/net-dhcp/network.py +++ b/net-dhcp/network.py @@ -354,6 +354,15 @@ class ContainerDHCPManager: elif event_type == udhcpc.EventType.BOUND: logger.info('[dhcp container] BOUND Event %s', _event) + result = subprocess.run(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'route', 'show', 'type', 'unicast', 'proto', 'static', 'table', 'all'], timeout=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + if result.returncode == 0: + routes = result.stdout + routes = routes.splitlines() + if routes: + logger.info('[dhcp container] Store existing static routes') + for route in routes: + logger.info('[dhcp container] Stored static route: %s', route) + logger.info('[dhcp container] Flushing IP addresses') subprocess.check_call(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'address', 'flush', 'dev', str(dhcp.iface['ifname']), 'label', str(dhcp.iface['ifname'])], @@ -369,6 +378,14 @@ class ContainerDHCPManager: subprocess.check_call(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'route', 'replace', 'default', 'via', str(dhcp.gateway)], timeout=1, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + if routes: + logger.info('[dhcp container] Restore static routes') + for route in routes: + parts = route.split() + command = ['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'route', 'add'] + parts + ['proto', 'static'] + output = subprocess.run(command, timeout=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + logger.info('[dhcp container] Restored static route: %s', route) else: logger.info('[dhcp container] Unhandled Event %s: %s', event_type,_event)