From e16d8bf6fd2d5205aa57d68dc6c9bfc7f23a78b4 Mon Sep 17 00:00:00 2001 From: yu Date: Sun, 18 Aug 2024 15:43:14 +0200 Subject: [PATCH 1/2] add snort manager --- .../tests/test_start_host_manager.py | 60 ++++--- .../tests/test_start_snort_manager.py | 162 ++++++++++++++++++ 2 files changed, 194 insertions(+), 28 deletions(-) create mode 100644 emulation-system/tests/test_start_snort_manager.py diff --git a/emulation-system/tests/test_start_host_manager.py b/emulation-system/tests/test_start_host_manager.py index f056518ab..612a0cecb 100644 --- a/emulation-system/tests/test_start_host_manager.py +++ b/emulation-system/tests/test_start_host_manager.py @@ -1,17 +1,17 @@ +from typing import List, Any, Generator import pytest -import docker import logging +import docker import grpc from unittest.mock import MagicMock from docker.types import IPAMConfig, IPAMPool import time from csle_common.dao.emulation_config.emulation_env_config import EmulationEnvConfig -from csle_common.util.emulation_util import EmulationUtil import csle_common.constants.constants as constants -from csle_common.controllers.host_controller import HostController import csle_collector.host_manager.host_manager_pb2_grpc import csle_collector.host_manager.host_manager_pb2 -from IPython.lib.editorhooks import emacs +import csle_collector.host_manager.query_host_manager +from csle_common.metastore.metastore_facade import MetastoreFacade @pytest.fixture(scope="module") @@ -25,7 +25,7 @@ def docker_client() -> None: @pytest.fixture(scope="module") -def network(docker_client) -> None: +def network(docker_client) -> Generator: """ Create a custom network with a specific subnet @@ -34,14 +34,16 @@ def network(docker_client) -> None: :return: None """ - ipam_pool = IPAMPool(subnet="15.15.15.0/24") + subnet = "15.15.15.0/24" + ipam_pool = IPAMPool(subnet=subnet) ipam_config = IPAMConfig(pool_configs=[ipam_pool]) + logging.info(f"Creating virtual network with subnet: {subnet}") network = docker_client.networks.create("test_network", driver="bridge", ipam=ipam_config) yield network network.remove() -def get_derived_containers(docker_client, excluded_tag="blank") -> None: +def get_derived_containers(docker_client, excluded_tag=constants.CONTAINER_IMAGES.BLANK) -> List[Any]: """ Get all the containers except the blank ones @@ -50,20 +52,18 @@ def get_derived_containers(docker_client, excluded_tag="blank") -> None: :return: None """ # Get all images except those with the excluded tag - match_tag = "0.6.0" + config = MetastoreFacade.get_config(id=1) + match_tag = config.version all_images = docker_client.images.list() - derived_images = [ - image - for image in all_images - if any(match_tag in tag for tag in image.tags) - and all("base" not in tag for tag in image.tags) - and all(excluded_tag not in tag for tag in image.tags) - ] + derived_images = [image for image in all_images + if (any(match_tag in tag for tag in image.tags) + and all(constants.CONTAINER_IMAGES.BASE not in tag for tag in image.tags) + and all(excluded_tag not in tag for tag in image.tags))] return derived_images @pytest.fixture(scope="module", params=get_derived_containers(docker.from_env())) -def container_setup(request, docker_client, network) -> None: +def container_setup(request, docker_client, network) -> Generator: """ Starts a Docker container before running tests and ensures its stopped and removed after tests complete. @@ -75,14 +75,13 @@ def container_setup(request, docker_client, network) -> None: """ # Create and start each derived container image = request.param - container = docker_client.containers.create( - image.tags[0], # Use the first tag for the image - command="sh -c 'while true; do sleep 3600; done'", - detach=True, - ) + container = docker_client.containers.create(image.tags[0], command="sh -c 'while true; do sleep 3600; done'", + detach=True) network.connect(container) + logging.info(f"Starting container: {container.id} with image: {container.image.tags}") container.start() yield container + logging.info(f"Stopping and removing container: {container.id} with image: {container.image.tags}") container.stop() container.remove() @@ -92,7 +91,6 @@ def test_start_host_manager(container_setup) -> None: Start host_manager in a container :param container_setup: container_setup - :return: None """ failed_containers = [] @@ -108,7 +106,7 @@ def test_start_host_manager(container_setup) -> None: emulation_env_config.host_manager_config.host_manager_log_file = "host_manager.log" emulation_env_config.host_manager_config.host_manager_max_workers = 4 - ip = container_setup.attrs["NetworkSettings"]["IPAddress"] + ip = container_setup.attrs[constants.DOCKER.NETWORK_SETTINGS][constants.DOCKER.IP_ADDRESS_INFO] port = emulation_env_config.host_manager_config.host_manager_port try: # Start host_manager command @@ -119,13 +117,19 @@ def test_start_host_manager(container_setup) -> None: f"--logfile {emulation_env_config.host_manager_config.host_manager_log_file} " f"--maxworkers {emulation_env_config.host_manager_config.host_manager_max_workers}" ) + # Run cmd in the container - result = container_setup.exec_run(cmd, detach=True) + logging.info(f"Starting host manager in container: {container_setup.id} " + f"with image: {container_setup.image.tags}") + container_setup.exec_run(cmd, detach=True) + # Check if host_manager starts cmd = ( f"sh -c '{constants.COMMANDS.PS_AUX} | {constants.COMMANDS.GREP} " f"{constants.COMMANDS.SPACE_DELIM}{constants.TRAFFIC_COMMANDS.HOST_MANAGER_FILE_NAME}'" ) + logging.info(f"Verifying that host manager is running in container: {container_setup.id} " + f"with image: {container_setup.image.tags}") result = container_setup.exec_run(cmd) output = result.output.decode("utf-8") assert constants.COMMANDS.SEARCH_HOST_MANAGER in output, "Host manager is not running in the container" @@ -136,17 +140,17 @@ def test_start_host_manager(container_setup) -> None: status = csle_collector.host_manager.query_host_manager.get_host_status(stub=stub) assert status except Exception as e: - print(f"Error occurred in container {container_setup.name}: {e}") + logging.info(f"Error occurred in container {container_setup.name}: {e}") failed_containers.append(container_setup.name) containers_info.append( { "container_status": container_setup.status, "container_image": container_setup.image.tags, "name": container_setup.name, - "error": str(e), + "error": str(e) } ) if failed_containers: - print("Containers that failed to start the host manager:") - print(containers_info) + logging.info("Containers that failed to start the host manager:") + logging.info(containers_info) assert not failed_containers, f"T{failed_containers} failed" diff --git a/emulation-system/tests/test_start_snort_manager.py b/emulation-system/tests/test_start_snort_manager.py new file mode 100644 index 000000000..ab6cbc293 --- /dev/null +++ b/emulation-system/tests/test_start_snort_manager.py @@ -0,0 +1,162 @@ +from typing import List, Any, Generator +import pytest +import docker +import logging +import grpc +from unittest.mock import MagicMock +from docker.types import IPAMConfig, IPAMPool +import time +from csle_common.dao.emulation_config.emulation_env_config import EmulationEnvConfig +from csle_common.util.emulation_util import EmulationUtil +import csle_common.constants.constants as constants +from csle_common.controllers.snort_ids_controller import SnortIDSController +import csle_collector.snort_ids_manager.snort_ids_manager_pb2_grpc +import csle_collector.snort_ids_manager.snort_ids_manager_pb2 +from csle_common.metastore.metastore_facade import MetastoreFacade +from IPython.lib.editorhooks import emacs + + +@pytest.fixture(scope="module") +def docker_client() -> None: + """ + Initialize and Provide a Docker client instance for the test + + :return: None + """ + return docker.from_env() + + +@pytest.fixture(scope="module") +def network(docker_client) -> None: + """ + Create a custom network with a specific subnet + + :param docker_client: docker_client + :yield: network + + :return: None + """ + subnet = "15.15.15.0/24" + ipam_pool = IPAMPool(subnet=subnet) + ipam_config = IPAMConfig(pool_configs=[ipam_pool]) + logging.info(f"Creating virtual network with subnet: {subnet}") + network = docker_client.networks.create("test_network", driver="bridge", ipam=ipam_config) + yield network + network.remove() + + +def get_derived_containers(docker_client, excluded_tag=constants.CONTAINER_IMAGES.BLANK) -> List[Any]: + """ + Get all the containers except the blank ones + + :param docker_client: docker_client + + :return: None + """ + # Get all images except those with the excluded tag + config = MetastoreFacade.get_config(id=1) + match_tag = config.version + all_images = docker_client.images.list() + derived_images = [ + image + for image in all_images + if any(match_tag in tag for tag in image.tags) + and all(constants.CONTAINER_IMAGES.BASE not in tag for tag in image.tags) + and all(excluded_tag not in tag for tag in image.tags) + ] + return derived_images + + +@pytest.fixture(scope="module", params=get_derived_containers(docker.from_env())) +def container_setup(request, docker_client, network) -> Generator: + """ + Starts a Docker container before running tests and ensures its stopped and removed after tests complete. + + :param request: request + :param docker_client: docker_client + :yield: container + + :return: None + """ + # Create and start each derived container + image = request.param + container = docker_client.containers.create( + image.tags[0], + command="sh -c 'while true; do sleep 3600; done'", + detach=True, + ) + network.connect(container) + container.start() + yield container + logging.info(f"Stopping and removing container: {container.id} with image: {container.image.tags}") + container.stop() + container.remove() + + +def test_start_snort_manager(container_setup) -> None: + """ + Start snort_manager in a container + + :param container_setup: container_setup + + :return: None + """ + failed_containers = [] + containers_info = [] + container_setup.reload() + assert container_setup.status == "running" + # Mock emulation_env_config + emulation_env_config = MagicMock(spec=EmulationEnvConfig) + emulation_env_config.get_connection.return_value = MagicMock() + emulation_env_config.snort_ids_manager_config = MagicMock() + emulation_env_config.snort_ids_manager_config.snort_ids_manager_port = 50051 + emulation_env_config.snort_ids_manager_config.snort_ids_manager_log_dir = "/var/log/snort" + emulation_env_config.snort_ids_manager_config.snort_ids_manager_log_file = "snort.log" + emulation_env_config.snort_ids_manager_config.snort_ids_manager_max_workers = 4 + + ip = container_setup.attrs[constants.DOCKER.NETWORK_SETTINGS][constants.DOCKER.IP_ADDRESS_INFO] + port = emulation_env_config.snort_ids_manager_config.snort_ids_manager_port + try: + # Start host_manager command + cmd = ( + f"/root/miniconda3/bin/python3 /snort_ids_manager.py " + f"--port {emulation_env_config.snort_ids_manager_config.snort_ids_manager_port} " + f"--logdir {emulation_env_config.snort_ids_manager_config.snort_ids_manager_log_dir} " + f"--logfile {emulation_env_config.snort_ids_manager_config.snort_ids_manager_log_file} " + f"--maxworkers {emulation_env_config.snort_ids_manager_config.snort_ids_manager_max_workers}" + ) + # Run cmd in the container + logging.info(f"Starting snort manager in container: {container_setup.id} " + f"with image: {container_setup.image.tags}") + container_setup.exec_run(cmd, detach=True) + # Check if host_manager starts + cmd = ( + f"sh -c '{constants.COMMANDS.PS_AUX} | {constants.COMMANDS.GREP} " + f"{constants.COMMANDS.SPACE_DELIM}{constants.TRAFFIC_COMMANDS.SNORT_IDS_MANAGER_FILE_NAME}'" + ) + logging.info(f"Verifying that snort manager is running in container: {container_setup.id} " + f"with image: {container_setup.image.tags}") + result = container_setup.exec_run(cmd) + output = result.output.decode("utf-8") + assert constants.COMMANDS.SEARCH_SNORT_IDS_MANAGER in output, "Snort manager is not running in the container" + time.sleep(5) + # Call grpc + with grpc.insecure_channel(f"{ip}:{port}", options=constants.GRPC_SERVERS.GRPC_OPTIONS) as channel: + stub = csle_collector.snort_ids_manager.snort_ids_manager_pb2_grpc.SnortIdsManagerStub(channel) + status = csle_collector.snort_ids_manager.query_snort_ids_manager.get_snort_ids_monitor_status(stub=stub) + assert status + except Exception as e: + print(f"Error occurred in container {container_setup.name}: {e}") + failed_containers.append(container_setup.name) + containers_info.append( + { + "container_status": container_setup.status, + "container_image": container_setup.image.tags, + "name": container_setup.name, + "error": str(e), + } + ) + if failed_containers: + logging.info("Containers that failed to start the snort manager:") + logging.info(containers_info) + assert not failed_containers, f"T{failed_containers} failed" From 25a394b669df8a58fb52fb9a6ed0165ed2f1565a Mon Sep 17 00:00:00 2001 From: yu Date: Sun, 18 Aug 2024 16:19:37 +0200 Subject: [PATCH 2/2] fix --- emulation-system/tests/test_start_snort_manager.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/emulation-system/tests/test_start_snort_manager.py b/emulation-system/tests/test_start_snort_manager.py index ab6cbc293..613e02b4e 100644 --- a/emulation-system/tests/test_start_snort_manager.py +++ b/emulation-system/tests/test_start_snort_manager.py @@ -64,7 +64,7 @@ def get_derived_containers(docker_client, excluded_tag=constants.CONTAINER_IMAGE and all(constants.CONTAINER_IMAGES.BASE not in tag for tag in image.tags) and all(excluded_tag not in tag for tag in image.tags) ] - return derived_images + return derived_images @pytest.fixture(scope="module", params=get_derived_containers(docker.from_env())) @@ -129,7 +129,7 @@ def test_start_snort_manager(container_setup) -> None: logging.info(f"Starting snort manager in container: {container_setup.id} " f"with image: {container_setup.image.tags}") container_setup.exec_run(cmd, detach=True) - # Check if host_manager starts + # Check if snort_manager starts cmd = ( f"sh -c '{constants.COMMANDS.PS_AUX} | {constants.COMMANDS.GREP} " f"{constants.COMMANDS.SPACE_DELIM}{constants.TRAFFIC_COMMANDS.SNORT_IDS_MANAGER_FILE_NAME}'"