From 56699d2377a706c54648b54c5fb72456fbc1961d Mon Sep 17 00:00:00 2001 From: Charlie Crane Date: Wed, 12 Feb 2025 16:18:50 +0000 Subject: [PATCH 1/4] Resolve hardcoding of Agent Logger having agent_name as abstract_agent --- src/primaite/game/agent/interface.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/primaite/game/agent/interface.py b/src/primaite/game/agent/interface.py index a55cd3ff..82edab88 100644 --- a/src/primaite/game/agent/interface.py +++ b/src/primaite/game/agent/interface.py @@ -70,7 +70,7 @@ class AbstractAgent(BaseModel, ABC): config: ConfigSchema = Field(default_factory=lambda: AbstractAgent.ConfigSchema()) - logger: AgentLog = AgentLog(agent_name="Abstract_Agent") + logger: AgentLog = None history: List[AgentHistoryItem] = [] action_manager: ActionManager = Field(default_factory=lambda: ActionManager()) @@ -79,6 +79,12 @@ class AbstractAgent(BaseModel, ABC): _registry: ClassVar[Dict[str, Type[AbstractAgent]]] = {} + def __init__(self, **kwargs): + """init""" + + super().__init__(**kwargs) + self.logger: AgentLog = AgentLog(agent_name=kwargs["config"]["ref"]) + def __init_subclass__(cls, discriminator: Optional[str] = None, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) if discriminator is None: From 7e138d1d61b9e1e2fad0bf5fd9e00ba4e4ea7701 Mon Sep 17 00:00:00 2001 From: Charlie Crane Date: Fri, 14 Feb 2025 11:38:15 +0000 Subject: [PATCH 2/4] #Bug and test fixes --- src/primaite/game/agent/interface.py | 2 +- src/primaite/simulator/network/container.py | 65 ++++++++----------- .../simulator/network/hardware/base.py | 4 +- src/primaite/simulator/system/software.py | 2 + .../extensions/nodes/giga_switch.py | 2 +- .../actions/test_terminal_actions.py | 2 - .../_primaite/_game/_agent/test_agent.py | 2 +- 7 files changed, 34 insertions(+), 45 deletions(-) diff --git a/src/primaite/game/agent/interface.py b/src/primaite/game/agent/interface.py index 82edab88..571c850d 100644 --- a/src/primaite/game/agent/interface.py +++ b/src/primaite/game/agent/interface.py @@ -80,7 +80,7 @@ class AbstractAgent(BaseModel, ABC): _registry: ClassVar[Dict[str, Type[AbstractAgent]]] = {} def __init__(self, **kwargs): - """init""" + """Initialise and setup agent logger""" super().__init__(**kwargs) self.logger: AgentLog = AgentLog(agent_name=kwargs["config"]["ref"]) diff --git a/src/primaite/simulator/network/container.py b/src/primaite/simulator/network/container.py index 2e494910..1fa8c680 100644 --- a/src/primaite/simulator/network/container.py +++ b/src/primaite/simulator/network/container.py @@ -163,15 +163,6 @@ class Network(SimComponent): :param links: Include link details in the output. Defaults to True. :param markdown: Use Markdown style in table output. Defaults to False. """ - nodes_type_map = { - "Router": self.router_nodes, - "Firewall": self.firewall_nodes, - "Switch": self.switch_nodes, - "Server": self.server_nodes, - "Computer": self.computer_nodes, - "Printer": self.printer_nodes, - "Wireless Router": self.wireless_router_nodes, - } if nodes: table = PrettyTable(["Node", "Type", "Operating State"]) @@ -189,19 +180,18 @@ class Network(SimComponent): table.set_style(MARKDOWN) table.align = "l" table.title = "IP Addresses" - for nodes in nodes_type_map.values(): - for node in nodes: - for i, port in node.network_interface.items(): - if hasattr(port, "ip_address"): - if port.ip_address != IPv4Address("127.0.0.1"): - port_str = port.port_name if port.port_name else port.port_num - table.add_row( - [ - node.config.hostname, - port_str, - port.ip_address, - port.subnet_mask, - node.config.default_gateway, + for node in self.nodes.values(): + for i, port in node.network_interface.items(): + if hasattr(port, "ip_address"): + if port.ip_address != IPv4Address("127.0.0.1"): + port_str = port.port_name if port.port_name else port.port_num + table.add_row( + [ + node.config.hostname, + port_str, + port.ip_address, + port.subnet_mask, + node.config.default_gateway, ] ) print(table) @@ -215,22 +205,21 @@ class Network(SimComponent): table.align = "l" table.title = "Links" links = list(self.links.values()) - for nodes in nodes_type_map.values(): - for node in nodes: - for link in links[::-1]: - if node in [link.endpoint_a.parent, link.endpoint_b.parent]: - table.add_row( - [ - link.endpoint_a.parent.config.hostname, - str(link.endpoint_a), - link.endpoint_b.parent.config.hostname, - str(link.endpoint_b), - link.is_up, - link.bandwidth, - link.current_load_percent, - ] - ) - links.remove(link) + for node in self.nodes.values(): + for link in links[::-1]: + if node in [link.endpoint_a.parent, link.endpoint_b.parent]: + table.add_row( + [ + link.endpoint_a.parent.config.hostname, + str(link.endpoint_a), + link.endpoint_b.parent.config.hostname, + str(link.endpoint_b), + link.is_up, + link.bandwidth, + link.current_load_percent, + ] + ) + links.remove(link) print(table) def clear_links(self): diff --git a/src/primaite/simulator/network/hardware/base.py b/src/primaite/simulator/network/hardware/base.py index 8653359a..4c252050 100644 --- a/src/primaite/simulator/network/hardware/base.py +++ b/src/primaite/simulator/network/hardware/base.py @@ -1197,7 +1197,7 @@ class UserSessionManager(Service, discriminator="user-session-manager"): """Request should take the form [username, password, remote_ip_address].""" username, password, remote_ip_address = request response = RequestResponse.from_bool(self.remote_login(username, password, remote_ip_address)) - response.data = {"remote_hostname": self.parent.hostname, "username": username} + response.data = {"remote_hostname": self.parent.config.hostname, "username": username} return response rm.add_request("remote_login", RequestType(func=_remote_login)) @@ -1230,7 +1230,7 @@ class UserSessionManager(Service, discriminator="user-session-manager"): if markdown: table.set_style(MARKDOWN) table.align = "l" - table.title = f"{self.parent.hostname} User Sessions" + table.title = f"{self.parent.config.hostname} User Sessions" def _add_session_to_table(user_session: UserSession): """ diff --git a/src/primaite/simulator/system/software.py b/src/primaite/simulator/system/software.py index 950f77c6..42468057 100644 --- a/src/primaite/simulator/system/software.py +++ b/src/primaite/simulator/system/software.py @@ -20,6 +20,7 @@ from primaite.utils.validation.port import Port if TYPE_CHECKING: from primaite.simulator.system.core.software_manager import SoftwareManager + from primaite.simulator.network.hardware.base import Node class SoftwareType(Enum): @@ -110,6 +111,7 @@ class Software(SimComponent, ABC): "The folder on the file system the Software uses." _fixing_countdown: Optional[int] = None "Current number of ticks left to patch the software." + # parent: Optional[Node] = None def __init__(self, **kwargs): super().__init__(**kwargs) diff --git a/tests/integration_tests/extensions/nodes/giga_switch.py b/tests/integration_tests/extensions/nodes/giga_switch.py index d9599618..5c202ed2 100644 --- a/tests/integration_tests/extensions/nodes/giga_switch.py +++ b/tests/integration_tests/extensions/nodes/giga_switch.py @@ -49,7 +49,7 @@ class GigaSwitch(NetworkNode, discriminator="gigaswitch"): if markdown: table.set_style(MARKDOWN) table.align = "l" - table.title = f"{self.hostname} Switch Ports" + table.title = f"{self.config.hostname} Switch Ports" for port_num, port in self.network_interface.items(): table.add_row([port_num, port.mac_address, port.speed, "Enabled" if port.enabled else "Disabled"]) print(table) diff --git a/tests/integration_tests/game_layer/actions/test_terminal_actions.py b/tests/integration_tests/game_layer/actions/test_terminal_actions.py index c39d8263..6d30644c 100644 --- a/tests/integration_tests/game_layer/actions/test_terminal_actions.py +++ b/tests/integration_tests/game_layer/actions/test_terminal_actions.py @@ -106,7 +106,6 @@ def test_remote_login_change_password(game_and_agent_fixture: Tuple[PrimaiteGame "username": "user123", "current_password": "password", "new_password": "different_password", - "remote_ip": str(server_1.network_interface[1].ip_address), }, ) agent.store_action(action) @@ -146,7 +145,6 @@ def test_change_password_logs_out_user(game_and_agent_fixture: Tuple[PrimaiteGam "username": "user123", "current_password": "password", "new_password": "different_password", - "remote_ip": str(server_1.network_interface[1].ip_address), }, ) agent.store_action(action) diff --git a/tests/unit_tests/_primaite/_game/_agent/test_agent.py b/tests/unit_tests/_primaite/_game/_agent/test_agent.py index a2693591..064537c2 100644 --- a/tests/unit_tests/_primaite/_game/_agent/test_agent.py +++ b/tests/unit_tests/_primaite/_game/_agent/test_agent.py @@ -4,7 +4,7 @@ from primaite.game.agent.scripted_agents.random_agent import RandomAgent def test_creating_empty_agent(): - agent = RandomAgent() + agent = RandomAgent(config={"ref" :"Empty Agent"}) assert len(agent.action_manager.action_map) == 0 assert isinstance(agent.observation_manager.obs, NullObservation) assert len(agent.reward_function.reward_components) == 0 From 7b80d15d8131bc5203c0a34b676746d572700486 Mon Sep 17 00:00:00 2001 From: Charlie Crane Date: Fri, 14 Feb 2025 11:39:25 +0000 Subject: [PATCH 3/4] # Pre-commit actions --- docs/source/how_to_guides/extensible_nodes.rst | 2 +- src/primaite/game/agent/interface.py | 3 +-- src/primaite/simulator/network/container.py | 5 ++--- src/primaite/simulator/system/software.py | 1 - tests/unit_tests/_primaite/_game/_agent/test_agent.py | 2 +- 5 files changed, 5 insertions(+), 8 deletions(-) diff --git a/docs/source/how_to_guides/extensible_nodes.rst b/docs/source/how_to_guides/extensible_nodes.rst index 043d0f06..4819cbb2 100644 --- a/docs/source/how_to_guides/extensible_nodes.rst +++ b/docs/source/how_to_guides/extensible_nodes.rst @@ -52,4 +52,4 @@ class Router(NetworkNode, identifier="router"): Changes to YAML file. ===================== -While effort has been made to ensure that nodes defined within configuration YAML files for use with PrimAITE 3.X remain compatible with PrimAITE v4+, it is encouraged to review for minor changes needed. +While effort has been made to ensure that nodes defined within configuration YAML files for use with PrimAITE 3.X remain compatible with PrimAITE v4+, it is encouraged to review for minor changes needed. diff --git a/src/primaite/game/agent/interface.py b/src/primaite/game/agent/interface.py index 571c850d..07363012 100644 --- a/src/primaite/game/agent/interface.py +++ b/src/primaite/game/agent/interface.py @@ -80,8 +80,7 @@ class AbstractAgent(BaseModel, ABC): _registry: ClassVar[Dict[str, Type[AbstractAgent]]] = {} def __init__(self, **kwargs): - """Initialise and setup agent logger""" - + """Initialise and setup agent logger.""" super().__init__(**kwargs) self.logger: AgentLog = AgentLog(agent_name=kwargs["config"]["ref"]) diff --git a/src/primaite/simulator/network/container.py b/src/primaite/simulator/network/container.py index 1fa8c680..b0426537 100644 --- a/src/primaite/simulator/network/container.py +++ b/src/primaite/simulator/network/container.py @@ -163,7 +163,6 @@ class Network(SimComponent): :param links: Include link details in the output. Defaults to True. :param markdown: Use Markdown style in table output. Defaults to False. """ - if nodes: table = PrettyTable(["Node", "Type", "Operating State"]) if markdown: @@ -192,8 +191,8 @@ class Network(SimComponent): port.ip_address, port.subnet_mask, node.config.default_gateway, - ] - ) + ] + ) print(table) if links: diff --git a/src/primaite/simulator/system/software.py b/src/primaite/simulator/system/software.py index 42468057..8fb64d73 100644 --- a/src/primaite/simulator/system/software.py +++ b/src/primaite/simulator/system/software.py @@ -20,7 +20,6 @@ from primaite.utils.validation.port import Port if TYPE_CHECKING: from primaite.simulator.system.core.software_manager import SoftwareManager - from primaite.simulator.network.hardware.base import Node class SoftwareType(Enum): diff --git a/tests/unit_tests/_primaite/_game/_agent/test_agent.py b/tests/unit_tests/_primaite/_game/_agent/test_agent.py index 064537c2..b555f1b2 100644 --- a/tests/unit_tests/_primaite/_game/_agent/test_agent.py +++ b/tests/unit_tests/_primaite/_game/_agent/test_agent.py @@ -4,7 +4,7 @@ from primaite.game.agent.scripted_agents.random_agent import RandomAgent def test_creating_empty_agent(): - agent = RandomAgent(config={"ref" :"Empty Agent"}) + agent = RandomAgent(config={"ref": "Empty Agent"}) assert len(agent.action_manager.action_map) == 0 assert isinstance(agent.observation_manager.obs, NullObservation) assert len(agent.reward_function.reward_components) == 0 From 22b197a79aaf287895398083e75396a1c9d7c04f Mon Sep 17 00:00:00 2001 From: Charlie Crane Date: Tue, 18 Feb 2025 09:13:33 +0000 Subject: [PATCH 4/4] Removal of leftover comment from software.py --- src/primaite/simulator/system/software.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/primaite/simulator/system/software.py b/src/primaite/simulator/system/software.py index 8fb64d73..950f77c6 100644 --- a/src/primaite/simulator/system/software.py +++ b/src/primaite/simulator/system/software.py @@ -110,7 +110,6 @@ class Software(SimComponent, ABC): "The folder on the file system the Software uses." _fixing_countdown: Optional[int] = None "Current number of ticks left to patch the software." - # parent: Optional[Node] = None def __init__(self, **kwargs): super().__init__(**kwargs)