Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
dboulware committed Jan 22, 2024
1 parent 5b60c10 commit 8ee8c64
Show file tree
Hide file tree
Showing 6 changed files with 189 additions and 97 deletions.
26 changes: 15 additions & 11 deletions src/initialization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
status_monitor = StatusMonitor()


def usb_exists() -> bool:
def usb_device_exists() -> bool:
logger.debug("Checking for USB...")
if settings.USB_DEVICE is not None:
usb_devices = check_output("lsusb").decode(sys.stdout.encoding)
Expand All @@ -36,22 +36,27 @@ def status_registration_handler(sender, **kwargs):
logger.exception("Error registering status component")


def set_container_unhealthy():
if settings.IN_DOCKER:
logger.warning("Signal analyzer is not healthy. Marking container for restart.")
Path(settings.SDR_HEALTHCHECK_FILE).touch()


try:
register_component_with_status.connect(status_registration_handler)
usb_exists = usb_exists()
if usb_exists:
usb_device_exists = usb_device_exists()
if usb_device_exists:
action_loader = ActionLoader()
logger.debug("test")
logger.debug(f"Actions ActionLoader has {len(action_loader.actions)} actions")
capabilities_loader = CapabilitiesLoader()
logger.debug("Calling sensor loader.")
sensor_loader = SensorLoader(capabilities_loader.capabilities)
if not sensor_loader.sensor.signal_analyzer.healthy():
if settings.IN_DOCKER:
logger.warning(
"Signal analyzer is not healthy. Marking container for restart."
)
Path(settings.SDR_HEALTHCHECK_FILE).touch()
if (
not settings.RUNNING_MIGRATIONS
and not sensor_loader.sensor.signal_analyzer.healthy()
):
set_container_unhealthy()
else:
action_loader = types.SimpleNamespace()
action_loader.actions = {}
Expand All @@ -64,7 +69,6 @@ def status_registration_handler(sender, **kwargs):
sensor_loader.switches = {}
sensor_loader.capabilities = {}
logger.warning("Usb is not ready. Marking container as unhealthy")
if settings.IN_DOCKER:
Path(settings.SDR_HEALTHCHECK_FILE).touch()
set_container_unhealthy()
except Exception as ex:
logger.error(f"Error during initialization: {ex}")
65 changes: 44 additions & 21 deletions src/initialization/action_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,56 @@
import os
import pkgutil
import shutil
from typing import Dict

from django.conf import settings
from scos_actions.actions import action_classes
from scos_actions.discover import test_actions
from scos_actions.discover import init
from scos_actions.discover import init, test_actions
from scos_actions.interfaces.action import Action

logger = logging.getLogger(__name__)

class ActionLoader(object):

class ActionLoader:
"""
Loads actions from scos_ plugins and any yaml configurations
in the configs/actions directory. Note: this class is a
singleton so other applications may safely create an instance
and reference the .actions property.
"""

_instance = None

def __init__(self):
if not hasattr(self, "actions"):
logger.debug("Actions have not been loaded. Loading actions...")
self.actions = load_actions_and_sigan(settings.MOCK_SIGAN, settings.RUNNING_TESTS, settings.DRIVERS_DIR,
settings.ACTIONS_DIR)
self._actions = load_actions(
settings.MOCK_SIGAN,
settings.RUNNING_TESTS,
settings.DRIVERS_DIR,
settings.ACTIONS_DIR,
)
else:
logger.debug("Already loaded actions. ")

def __new__(cls):
if cls._instance is None:
logger.debug('Creating the ActionLoader')
cls._instance = super(ActionLoader, cls).__new__(cls)
logger.debug(f"Calling load_actions with {settings.MOCK_SIGAN}, {settings.RUNNING_TESTS}, {settings.DRIVERS_DIR}, {settings.ACTIONS_DIR}")
logger.debug("Creating the ActionLoader")
cls._instance = super().__new__(cls)
logger.debug(
f"Calling load_actions with {settings.MOCK_SIGAN}, {settings.RUNNING_TESTS}, {settings.DRIVERS_DIR}, {settings.ACTIONS_DIR}"
)
return cls._instance

def copy_driver_files(driver_dir):
@property
def actions(self) -> Dict[str, Action]:
"""
Returns all sensor actions configured in the system.
"""
return self._actions


def copy_driver_files(driver_dir: str):
"""Copy driver files where they need to go"""
logger.debug(f"Copying driver files in {driver_dir}")
for root, dirs, files in os.walk(driver_dir):
Expand All @@ -43,9 +67,7 @@ def copy_driver_files(driver_dir):
if type(json_data) == dict and "scos_files" in json_data:
scos_files = json_data["scos_files"]
for scos_file in scos_files:
source_path = os.path.join(
driver_dir, scos_file["source_path"]
)
source_path = os.path.join(driver_dir, scos_file["source_path"])
if not os.path.isfile(source_path):
logger.error(f"Unable to find file at {source_path}")
continue
Expand All @@ -60,8 +82,10 @@ def copy_driver_files(driver_dir):
logger.error(f"Failed to copy {source_path} to {dest_path}")
logger.error(e)

def load_actions_and_sigan(mock_sigan, running_tests, driver_dir, action_dir):

def load_actions(
mock_sigan: bool, running_tests: bool, driver_dir: str, action_dir: str
):
logger.debug("********** Initializing actions **********")
copy_driver_files(driver_dir) # copy driver files before loading plugins
discovered_plugins = {
Expand All @@ -71,7 +95,6 @@ def load_actions_and_sigan(mock_sigan, running_tests, driver_dir, action_dir):
}
logger.debug(discovered_plugins)
actions = {}
signal_analyzer = None
if mock_sigan or running_tests:
logger.debug(f"Loading {len(test_actions)} test actions.")
actions.update(test_actions)
Expand All @@ -82,16 +105,16 @@ def load_actions_and_sigan(mock_sigan, running_tests, driver_dir, action_dir):
if hasattr(discover, "actions"):
logger.debug(f"loading {len(discover.actions)} actions.")
actions.update(discover.actions)
if hasattr(discover, "action_classes") and discover.action_classes is not None:
if (
hasattr(discover, "action_classes")
and discover.action_classes is not None
):
action_classes.update(discover.action_classes)
# if hasattr(discover, "signal_analyzer") and discover.signal_analyzer is not None:
# logger.debug(f"Found signal_analyzer: {discover.signal_analyzer}")
# signal_analyzer = discover.signal_analyzer
# else:
# logger.debug(f"{discover} has no signal_analyzer attribute")

logger.debug(f"Loading actions in {action_dir}")
yaml_actions, yaml_test_actions = init(action_classes=action_classes, yaml_dir=action_dir)
yaml_actions, yaml_test_actions = init(
action_classes=action_classes, yaml_dir=action_dir
)
actions.update(yaml_actions)
logger.debug("Finished loading and registering actions")
return actions
7 changes: 7 additions & 0 deletions src/initialization/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,11 @@


class InitializationConfig(AppConfig):
"""
The first application to load. This application is responsible
for initializing the hardware components and loading actions.
This ensures the components are initialized in the appropriate
order and available for the other applications.
"""

name = "initialization"
9 changes: 7 additions & 2 deletions src/initialization/capabilities_loader.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import hashlib
import json
import logging

from django.conf import settings
from scos_actions.utils import load_from_json

Expand All @@ -13,7 +14,7 @@ class CapabilitiesLoader:
def __init__(self):
if not hasattr(self, "capabilities"):
logger.debug("Capabilities have not been loaded. Loading...")
self.capabilities = load_capabilities(settings.SENSOR_DEFINITION_FILE)
self._capabilities = load_capabilities(settings.SENSOR_DEFINITION_FILE)
else:
logger.debug("Already loaded capabilities. ")

Expand All @@ -23,8 +24,12 @@ def __new__(cls):
cls._instance = super().__new__(cls)
return cls._instance

@property
def capabilities(self) -> dict:
return self._capabilities


def load_capabilities(sensor_definition_file) -> dict:
def load_capabilities(sensor_definition_file: str) -> dict:
capabilities = {}
sensor_definition_hash = None
sensor_location = None
Expand Down
Loading

0 comments on commit 8ee8c64

Please sign in to comment.