From 0527904c488476f271eb44a6284fc75ba042d733 Mon Sep 17 00:00:00 2001 From: Eric Callahan Date: Tue, 29 Jun 2021 20:02:54 -0400 Subject: [PATCH] moonraker: remove references to "system_args" Rather than add these arguments to the config, use a method to access them from the server object. Signed-off-by: Eric Callahan --- moonraker/app.py | 2 +- moonraker/components/klippy_apis.py | 4 ++-- moonraker/components/octoprint_compat.py | 3 ++- moonraker/confighelper.py | 11 ++-------- moonraker/moonraker.py | 28 ++++++++++++++---------- moonraker/utils.py | 24 ++++++++++---------- 6 files changed, 34 insertions(+), 38 deletions(-) diff --git a/moonraker/app.py b/moonraker/app.py index f3fe5db..c769522 100644 --- a/moonraker/app.py +++ b/moonraker/app.py @@ -173,7 +173,7 @@ class MoonrakerApp: self.get_handler_delegate = self.app.get_handler_delegate # Register handlers - logfile = config['system_args'].get('logfile') + logfile = self.server.get_app_args().get('log_file') if logfile: self.register_static_file_handler( "moonraker.log", logfile, force=True) diff --git a/moonraker/components/klippy_apis.py b/moonraker/components/klippy_apis.py index b52dea7..f8248ee 100644 --- a/moonraker/components/klippy_apis.py +++ b/moonraker/components/klippy_apis.py @@ -39,8 +39,8 @@ SENTINEL = SentinelClass.get_instance() class KlippyAPI(Subscribable): def __init__(self, config: ConfigHelper) -> None: self.server = config.get_server() - system_args = config['system_args'] - self.version = system_args.get('software_version') + app_args = self.server.get_app_args() + self.version = app_args.get('software_version') # Maintain a subscription for all moonraker requests, as # we do not want to overwrite them self.host_subscription: Subscription = {} diff --git a/moonraker/components/octoprint_compat.py b/moonraker/components/octoprint_compat.py index 242c24a..a1782c1 100644 --- a/moonraker/components/octoprint_compat.py +++ b/moonraker/components/octoprint_compat.py @@ -38,7 +38,8 @@ class OctoprintCompat: def __init__(self, config: ConfigHelper) -> None: self.server = config.get_server() - self.software_version = config['system_args'].get('software_version') + self.software_version = self.server.get_app_args().get( + 'software_version') # Local variables self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis') diff --git a/moonraker/confighelper.py b/moonraker/confighelper.py index 55a2a5e..71fe616 100644 --- a/moonraker/confighelper.py +++ b/moonraker/confighelper.py @@ -7,7 +7,6 @@ from __future__ import annotations import configparser import os -import logging from utils import SentinelClass # Annotation imports @@ -15,7 +14,6 @@ from typing import ( TYPE_CHECKING, Any, Callable, - Type, IO, TypeVar, Union, @@ -23,7 +21,6 @@ from typing import ( List, ) if TYPE_CHECKING: - from argparse import Namespace from moonraker import Server _T = TypeVar("_T") ConfigVal = Union[None, int, float, bool, str] @@ -158,10 +155,10 @@ class ConfigHelper: "In the future this will result in a startup error.") def get_configuration(server: Server, - system_args: Namespace + app_args: Dict[str, Any] ) -> ConfigHelper: cfg_file_path: str = os.path.normpath(os.path.expanduser( - system_args.configfile)) + app_args['config_file'])) if not os.path.isfile(cfg_file_path): raise ConfigError( f"Configuration File Not Found: '{cfg_file_path}''") @@ -185,8 +182,4 @@ def get_configuration(server: Server, except Exception: pass - config['system_args'] = { - 'configfile': system_args.configfile, - 'logfile': system_args.logfile, - 'software_version': system_args.software_version} return ConfigHelper(server, config, 'server', orig_sections) diff --git a/moonraker/moonraker.py b/moonraker/moonraker.py index 9e34c06..5eeac88 100755 --- a/moonraker/moonraker.py +++ b/moonraker/moonraker.py @@ -60,10 +60,11 @@ SENTINEL = SentinelClass.get_instance() class Server: error = ServerError def __init__(self, - args: argparse.Namespace, + args: Dict[str, Any], file_logger: Optional[utils.MoonrakerLoggingHandler] ) -> None: self.file_logger = file_logger + self.app_args = args self.config = config = confighelper.get_configuration(self, args) # log config file strio = io.StringIO() @@ -138,6 +139,9 @@ class Server: self.klippy_apis: KlippyAPI = self.lookup_component('klippy_apis') config.validate_config() + def get_app_args(self) -> Dict[str, Any]: + return dict(self.app_args) + def start(self) -> None: hostname, hostport = self.get_host_info() logging.info( @@ -172,8 +176,8 @@ class Server: self.load_component(config, component) # check for optional components - opt_sections = set([s.split()[0] for s in config.sections()]) - \ - set(['server', 'system_args']) + opt_sections = set([s.split()[0] for s in config.sections()]) + opt_sections.remove('server') for section in opt_sections: self.load_component(config, section, None) @@ -722,18 +726,18 @@ def main() -> None: parser.add_argument( "-n", "--nologfile", action='store_true', help="disable logging to a file") - system_args = parser.parse_args() + cmd_line_args = parser.parse_args() + app_args = {'config_file': cmd_line_args.configfile} # Setup Logging version = utils.get_software_version() - if system_args.nologfile: - log_file = "" + if cmd_line_args.nologfile: + app_args['log_file'] = "" else: - log_file = os.path.normpath(os.path.expanduser( - system_args.logfile)) - system_args.logfile = log_file - system_args.software_version = version - ql, file_logger = utils.setup_logging(log_file, version) + app_args['log_file'] = os.path.normpath( + os.path.expanduser(cmd_line_args.logfile)) + app_args['software_version'] = version + ql, file_logger = utils.setup_logging(app_args) if sys.version_info < (3, 7): msg = f"Moonraker requires Python 3.7 or above. " \ @@ -748,7 +752,7 @@ def main() -> None: estatus = 0 while True: try: - server = Server(system_args, file_logger) + server = Server(app_args, file_logger) except Exception: logging.exception("Moonraker Error") estatus = 1 diff --git a/moonraker/utils.py b/moonraker/utils.py index 67e7524..f0766ee 100644 --- a/moonraker/utils.py +++ b/moonraker/utils.py @@ -21,7 +21,8 @@ from typing import ( Optional, ClassVar, Tuple, - Dict + Dict, + Any, ) class ServerError(Exception): @@ -53,15 +54,13 @@ class LocalQueueHandler(logging.handlers.QueueHandler): # Timed Rotating File Handler, based on Klipper's implementation class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler): - def __init__(self, - software_version: str, - filename: str, - **kwargs) -> None: - super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs) + def __init__(self, app_args: Dict[str, Any], **kwargs) -> None: + super().__init__(app_args['log_file'], **kwargs) self.rollover_info: Dict[str, str] = { - 'header': f"{'-'*20}Moonraker Log Start{'-'*20}", - 'version': f"Git Version: {software_version}", + 'header': f"{'-'*20}Moonraker Log Start{'-'*20}" } + self.rollover_info['application_args'] = "\n".join( + [f"{k}: {v}" for k, v in app_args.items()]) lines = [line for line in self.rollover_info.values() if line] if self.stream is not None: self.stream.write("\n".join(lines) + "\n") @@ -70,7 +69,7 @@ class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler): self.rollover_info[name] = item def doRollover(self) -> None: - super(MoonrakerLoggingHandler, self).doRollover() + super().doRollover() lines = [line for line in self.rollover_info.values() if line] if self.stream is not None: self.stream.write("\n".join(lines) + "\n") @@ -107,8 +106,7 @@ def get_software_version() -> str: version = "?" return version -def setup_logging(log_file: str, - software_version: str +def setup_logging(app_args: Dict[str, Any] ) -> Tuple[logging.handlers.QueueListener, Optional[MoonrakerLoggingHandler]]: root_logger = logging.getLogger() @@ -121,9 +119,9 @@ def setup_logging(log_file: str, '[%(filename)s:%(funcName)s()] - %(message)s') stdout_hdlr.setFormatter(stdout_fmt) file_hdlr = None - if log_file: + if app_args.get('log_file', ""): file_hdlr = MoonrakerLoggingHandler( - software_version, log_file, when='midnight', backupCount=2) + app_args, when='midnight', backupCount=2) formatter = logging.Formatter( '%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s') file_hdlr.setFormatter(formatter)