Skip to content

Commit

Permalink
refactor: Remove metaclass from network_state.py (#4638)
Browse files Browse the repository at this point in the history
It's magic that makes it hard to follow call hierachies without saving
much code.
  • Loading branch information
TheRealFalcon authored Nov 29, 2023
1 parent 05f039c commit 16ad372
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions cloudinit/net/network_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,25 +123,6 @@ def decorator(self, command, *args, **kwargs):
return wrapper


class CommandHandlerMeta(type):
"""Metaclass that dynamically creates a 'command_handlers' attribute.
This will scan the to-be-created class for methods that start with
'handle_' and on finding those will populate a class attribute mapping
so that those methods can be quickly located and called.
"""

def __new__(cls, name, parents, dct):
command_handlers = {}
for attr_name, attr in dct.items():
if callable(attr) and attr_name.startswith("handle_"):
handles_what = attr_name[len("handle_") :]
if handles_what:
command_handlers[handles_what] = attr
dct["command_handlers"] = command_handlers
return super(CommandHandlerMeta, cls).__new__(cls, name, parents, dct)


class NetworkState:
def __init__(
self, network_state: dict, version: int = NETWORK_STATE_VERSION
Expand Down Expand Up @@ -228,7 +209,7 @@ def to_passthrough(cls, network_state: dict) -> "NetworkState":
return cls({"config": network_state}, **kwargs)


class NetworkStateInterpreter(metaclass=CommandHandlerMeta):
class NetworkStateInterpreter:
initial_network_state = {
"interfaces": {},
"routes": [],
Expand All @@ -253,6 +234,21 @@ def __init__(
self._parsed = False
self._interface_dns_map: dict = {}
self._renderer = renderer
self.command_handlers = {
"bond": self.handle_bond,
"bonds": self.handle_bonds,
"bridge": self.handle_bridge,
"bridges": self.handle_bridges,
"ethernets": self.handle_ethernets,
"infiniband": self.handle_infiniband,
"loopback": self.handle_loopback,
"nameserver": self.handle_nameserver,
"physical": self.handle_physical,
"route": self.handle_route,
"vlan": self.handle_vlan,
"vlans": self.handle_vlans,
"wifis": self.handle_wifis,
}

@property
def network_state(self) -> NetworkState:
Expand Down Expand Up @@ -319,7 +315,7 @@ def parse_config_v1(self, skip_broken=True):
"No handler found for command '%s'" % command_type
) from e
try:
handler(self, command)
handler(command)
except InvalidCommand:
if not skip_broken:
raise
Expand Down Expand Up @@ -361,7 +357,7 @@ def parse_config_v2(self, skip_broken=True):
"No handler found for command '%s'" % command_type
) from e
try:
handler(self, command)
handler(command)
self._v2_common(command)
except InvalidCommand:
if not skip_broken:
Expand Down

0 comments on commit 16ad372

Please sign in to comment.