Skip to content

Commit

Permalink
Setting up the root controller within the ShellContext
Browse files Browse the repository at this point in the history
  • Loading branch information
PawelPlesniak committed Dec 9, 2024
1 parent e1252d6 commit 5d106bc
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 25 deletions.
3 changes: 0 additions & 3 deletions src/drunc/apps/__main_unified_shell__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@

def main():
from drunc.utils.utils import setup_root_logger
from drunc.unified_shell.context import UnifiedShellContext
setup_root_logger("ERROR")
context = UnifiedShellContext()

try:
Expand Down
24 changes: 14 additions & 10 deletions src/drunc/unified_shell/context.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
from drunc.utils.shell_utils import ShellContext, GRPCDriver, add_traceback_flag
from drunc.utils.utils import get_logger
from druncschema.token_pb2 import Token
from typing import Mapping

class UnifiedShellContext(ShellContext): # boilerplatefest
status_receiver_pm = None
status_receiver_controller = None
took_control = False
pm_process = None
address_pm = ''
address_controller = ''
boot_configuration = ''
session_name = ''
def __init__(self):
self.status_receiver_pm = None
self.status_receiver_controller = None
self.took_control = False
self.pm_process = None
self.address_pm = ''
self.address_controller = ''
self.boot_configuration = ''
self.session_name = ''
super(UnifiedShellContext, self).__init__()

def reset(self, address_pm:str=''):
self.address_pm = address_pm
self.log = get_logger("unified_shell", rich_handler = True)
super(UnifiedShellContext, self)._reset(
name = 'unified',
name = 'unified_shell',
token_args = {},
driver_args = {},
)

def create_drivers(self, **kwargs) -> Mapping[str, GRPCDriver]:
ret = {}

if self.address_pm != '':
from drunc.process_manager.process_manager_driver import ProcessManagerDriver
ret['process_manager'] = ProcessManagerDriver(
Expand Down Expand Up @@ -62,6 +65,7 @@ def start_listening_pm(self, broadcaster_conf):
from drunc.broadcast.client.broadcast_handler import BroadcastHandler
from drunc.broadcast.client.configuration import BroadcastClientConfHandler
from drunc.utils.configuration import ConfTypes
# self.log.error("Started liostending toj pm")
bcch = BroadcastClientConfHandler(
type = ConfTypes.ProtobufAny,
data = broadcaster_conf,
Expand Down
5 changes: 3 additions & 2 deletions src/drunc/utils/shell_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import abc
from druncschema.token_pb2 import Token
from druncschema.request_response_pb2 import Request
from drunc.utils.utils import get_logger, setup_root_logger
from typing import Mapping
from drunc.exceptions import DruncShellException

Expand Down Expand Up @@ -231,12 +232,12 @@ class ShellContext:
def _reset(self, name:str, token_args:dict={}, driver_args:dict={}):
from rich.console import Console
self._console = Console()
from drunc.utils.utils import get_logger
self.log = get_logger(f"{name}.shell")
self.log = get_logger(f"{name}.shell_context")
self._token = self.create_token(**token_args)
self._drivers: Mapping[str, GRPCDriver] = self.create_drivers(**driver_args)

def __init__(self, *args, **kwargs):
setup_root_logger("NOTSET")
try:
self.reset(*args, **kwargs)
except Exception as e:
Expand Down
30 changes: 20 additions & 10 deletions src/drunc/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,13 @@ def print_traceback(with_rich:bool=True): # RETURNTOME - make this false
def setup_root_logger(stream_log_level:str) -> None:
if stream_log_level not in log_levels.keys():
raise DruncSetupException(f"Unrecognised log level, should be one of {log_levels.keys()}.")
drunc_root_logger = logging.getLogger('drunc')
if "drunc" in logging.Logger.manager.loggerDict:
drunc_root_logger = logging.getLogger('drunc')
if drunc_root_logger.getEffectiveLevel() == log_levels["ERROR"]:
if drunc_root_logger.level == log_levels["NOTSET"]:
drunc_root_logger.setLevel(stream_log_level)
drunc_root_logger.info("'drunc' logger already exists, skipping setup")
return

logger = logging.getLogger('drunc')
stream_log_level = log_levels[stream_log_level]
logger.setLevel(stream_log_level)

Check failure on line 64 in src/drunc/utils/utils.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F821)

src/drunc/utils/utils.py:64:5: F821 Undefined name `logger`
for handler in logger.handlers:

Check failure on line 65 in src/drunc/utils/utils.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F821)

src/drunc/utils/utils.py:65:20: F821 Undefined name `logger`
Expand Down Expand Up @@ -90,29 +89,40 @@ def get_logger(logger_name:str, log_file_path:str = None, log_file_log_level:str
if logger_name == "process_manager" and not 'drunc.process_manager' in logging.Logger.manager.loggerDict and not log_file_path:
raise DruncSetupException("process_manager setup requires a log path.")

root_logger_level = logging.getLogger('drunc').level
if not log_file_log_level:
log_file_log_level = logging.getLogger('drunc').level
log_file_log_level = root_logger_level
if not rich_log_level:
rich_log_level = logging.getLogger('drunc').level
rich_log_level = root_logger_level

logger_name = 'drunc.' + logger_name
logger = logging.getLogger(logger_name)
if logger_name in logging.Logger.manager.loggerDict:
logger = logging.getLogger(logger_name)
logger.debug(f"Logger {logger_name} already exists, not overwriting properties")
return logger
if logger.level == log_levels["NOTSET"]:
logger.setLevel(logging.getLogger('drunc').level)
for handler in logger.handlers:
if type(handler)==RichHandler:
handler.setLevel(rich_log_level)
elif type(handler)==logging.FileHandler:
handler.setLevel(log_file_log_level)
else:
raise DruncSetupException(f"Unrecognised hanlder type {type(handler)}")
exit(1)
else:
logger.debug(f"Logger {logger_name} already exists, not overwriting handlers")
return logger

if logger_name == "process_manager" and not rich_handler:
raise DruncSetupException("process_manager requires a rich handler.")
if log_file_path and os.path.isfile(log_file_path):
os.remove(log_file_path)

logger = logging.getLogger(logger_name)
while logger.hasHandlers():
if len(logger.handlers) > 0:
logger.removeHandler(logger.handlers[0])
else:
break
logger.setLevel(logging.getLogger('drunc').getEffectiveLevel())
logger.setLevel(logging.getLogger('drunc').level)

if log_file_path:
fileHandler = logging.FileHandler(filename = log_file_path)
Expand Down

0 comments on commit 5d106bc

Please sign in to comment.