improve default route service to detect connected routers and use the addresses of the first one found

This commit is contained in:
Blake Harnden 2020-04-02 15:12:07 -07:00
parent 72189a5c28
commit 7d392c43ac
3 changed files with 34 additions and 30 deletions

View file

@ -1,10 +1,10 @@
import logging
from typing import Any, Dict
import netaddr
from core import utils
from core.configservice.base import ConfigService, ConfigServiceMode
from core.nodes.base import CoreNode
GROUP_NAME = "Utility"
@ -24,16 +24,21 @@ class DefaultRouteService(ConfigService):
modes = {}
def data(self) -> Dict[str, Any]:
addresses = []
for netif in self.node.netifs():
if getattr(netif, "control", False):
# only add default routes for linked routing nodes
routes = []
for other_node in self.node.session.nodes.values():
if not isinstance(other_node, CoreNode):
continue
for addr in netif.addrlist:
logging.info("default route address: %s", addr)
net = netaddr.IPNetwork(addr)
if net[1] != net[-2]:
addresses.append(net[1])
return dict(addresses=addresses)
if other_node.type not in ["router", "mdr"]:
continue
commonnets = self.node.commonnets(other_node)
if commonnets:
_, _, router_eth = commonnets[0]
for x in router_eth.addrlist:
addr, prefix = x.split("/")
routes.append(addr)
break
return dict(routes=routes)
class DefaultMulticastRouteService(ConfigService):

View file

@ -1,5 +1,5 @@
#!/bin/sh
# auto-generated by DefaultRoute service
% for address in addresses:
ip route add default via ${address}
% for route in routes:
ip route add default via ${route}
% endfor

View file

@ -1,13 +1,13 @@
"""
utility.py: defines miscellaneous utility services.
"""
import os
import netaddr
from core import constants, utils
from core.errors import CoreCommandError
from core.nodes.base import CoreNode
from core.services.coreservices import CoreService, ServiceMode
@ -77,27 +77,26 @@ class DefaultRouteService(UtilService):
@classmethod
def generate_config(cls, node, filename):
# only add default routes for linked routing nodes
routes = []
for other_node in node.session.nodes.values():
if not isinstance(other_node, CoreNode):
continue
if other_node.type not in ["router", "mdr"]:
continue
commonnets = node.commonnets(other_node)
if commonnets:
_, _, router_eth = commonnets[0]
for x in router_eth.addrlist:
addr, prefix = x.split("/")
routes.append(addr)
break
cfg = "#!/bin/sh\n"
cfg += "# auto-generated by DefaultRoute service (utility.py)\n"
for ifc in node.netifs():
if hasattr(ifc, "control") and ifc.control is True:
continue
cfg += "\n".join(map(cls.addrstr, ifc.addrlist))
cfg += "\n"
for route in routes:
cfg += f"ip route add default via {route}\n"
return cfg
@staticmethod
def addrstr(x):
net = netaddr.IPNetwork(x)
if net[1] == net[-2]:
return ""
else:
if os.uname()[0] == "Linux":
rtcmd = "ip route add default via"
else:
raise Exception("unknown platform")
return "%s %s" % (rtcmd, net[1])
class DefaultMulticastRouteService(UtilService):
name = "DefaultMulticastRoute"