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 <arksine.code@gmail.com>
This commit is contained in:
Eric Callahan 2021-06-29 20:02:54 -04:00
parent 3642003dd2
commit 0527904c48
6 changed files with 34 additions and 38 deletions

View File

@ -173,7 +173,7 @@ class MoonrakerApp:
self.get_handler_delegate = self.app.get_handler_delegate self.get_handler_delegate = self.app.get_handler_delegate
# Register handlers # Register handlers
logfile = config['system_args'].get('logfile') logfile = self.server.get_app_args().get('log_file')
if logfile: if logfile:
self.register_static_file_handler( self.register_static_file_handler(
"moonraker.log", logfile, force=True) "moonraker.log", logfile, force=True)

View File

@ -39,8 +39,8 @@ SENTINEL = SentinelClass.get_instance()
class KlippyAPI(Subscribable): class KlippyAPI(Subscribable):
def __init__(self, config: ConfigHelper) -> None: def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server() self.server = config.get_server()
system_args = config['system_args'] app_args = self.server.get_app_args()
self.version = system_args.get('software_version') self.version = app_args.get('software_version')
# Maintain a subscription for all moonraker requests, as # Maintain a subscription for all moonraker requests, as
# we do not want to overwrite them # we do not want to overwrite them
self.host_subscription: Subscription = {} self.host_subscription: Subscription = {}

View File

@ -38,7 +38,8 @@ class OctoprintCompat:
def __init__(self, config: ConfigHelper) -> None: def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server() 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 # Local variables
self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis') self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis')

View File

@ -7,7 +7,6 @@
from __future__ import annotations from __future__ import annotations
import configparser import configparser
import os import os
import logging
from utils import SentinelClass from utils import SentinelClass
# Annotation imports # Annotation imports
@ -15,7 +14,6 @@ from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
Callable, Callable,
Type,
IO, IO,
TypeVar, TypeVar,
Union, Union,
@ -23,7 +21,6 @@ from typing import (
List, List,
) )
if TYPE_CHECKING: if TYPE_CHECKING:
from argparse import Namespace
from moonraker import Server from moonraker import Server
_T = TypeVar("_T") _T = TypeVar("_T")
ConfigVal = Union[None, int, float, bool, str] ConfigVal = Union[None, int, float, bool, str]
@ -158,10 +155,10 @@ class ConfigHelper:
"In the future this will result in a startup error.") "In the future this will result in a startup error.")
def get_configuration(server: Server, def get_configuration(server: Server,
system_args: Namespace app_args: Dict[str, Any]
) -> ConfigHelper: ) -> ConfigHelper:
cfg_file_path: str = os.path.normpath(os.path.expanduser( 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): if not os.path.isfile(cfg_file_path):
raise ConfigError( raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''") f"Configuration File Not Found: '{cfg_file_path}''")
@ -185,8 +182,4 @@ def get_configuration(server: Server,
except Exception: except Exception:
pass 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) return ConfigHelper(server, config, 'server', orig_sections)

View File

@ -60,10 +60,11 @@ SENTINEL = SentinelClass.get_instance()
class Server: class Server:
error = ServerError error = ServerError
def __init__(self, def __init__(self,
args: argparse.Namespace, args: Dict[str, Any],
file_logger: Optional[utils.MoonrakerLoggingHandler] file_logger: Optional[utils.MoonrakerLoggingHandler]
) -> None: ) -> None:
self.file_logger = file_logger self.file_logger = file_logger
self.app_args = args
self.config = config = confighelper.get_configuration(self, args) self.config = config = confighelper.get_configuration(self, args)
# log config file # log config file
strio = io.StringIO() strio = io.StringIO()
@ -138,6 +139,9 @@ class Server:
self.klippy_apis: KlippyAPI = self.lookup_component('klippy_apis') self.klippy_apis: KlippyAPI = self.lookup_component('klippy_apis')
config.validate_config() config.validate_config()
def get_app_args(self) -> Dict[str, Any]:
return dict(self.app_args)
def start(self) -> None: def start(self) -> None:
hostname, hostport = self.get_host_info() hostname, hostport = self.get_host_info()
logging.info( logging.info(
@ -172,8 +176,8 @@ class Server:
self.load_component(config, component) self.load_component(config, component)
# check for optional components # check for optional components
opt_sections = set([s.split()[0] for s in config.sections()]) - \ opt_sections = set([s.split()[0] for s in config.sections()])
set(['server', 'system_args']) opt_sections.remove('server')
for section in opt_sections: for section in opt_sections:
self.load_component(config, section, None) self.load_component(config, section, None)
@ -722,18 +726,18 @@ def main() -> None:
parser.add_argument( parser.add_argument(
"-n", "--nologfile", action='store_true', "-n", "--nologfile", action='store_true',
help="disable logging to a file") 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 # Setup Logging
version = utils.get_software_version() version = utils.get_software_version()
if system_args.nologfile: if cmd_line_args.nologfile:
log_file = "" app_args['log_file'] = ""
else: else:
log_file = os.path.normpath(os.path.expanduser( app_args['log_file'] = os.path.normpath(
system_args.logfile)) os.path.expanduser(cmd_line_args.logfile))
system_args.logfile = log_file app_args['software_version'] = version
system_args.software_version = version ql, file_logger = utils.setup_logging(app_args)
ql, file_logger = utils.setup_logging(log_file, version)
if sys.version_info < (3, 7): if sys.version_info < (3, 7):
msg = f"Moonraker requires Python 3.7 or above. " \ msg = f"Moonraker requires Python 3.7 or above. " \
@ -748,7 +752,7 @@ def main() -> None:
estatus = 0 estatus = 0
while True: while True:
try: try:
server = Server(system_args, file_logger) server = Server(app_args, file_logger)
except Exception: except Exception:
logging.exception("Moonraker Error") logging.exception("Moonraker Error")
estatus = 1 estatus = 1

View File

@ -21,7 +21,8 @@ from typing import (
Optional, Optional,
ClassVar, ClassVar,
Tuple, Tuple,
Dict Dict,
Any,
) )
class ServerError(Exception): class ServerError(Exception):
@ -53,15 +54,13 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
# Timed Rotating File Handler, based on Klipper's implementation # Timed Rotating File Handler, based on Klipper's implementation
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler): class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, def __init__(self, app_args: Dict[str, Any], **kwargs) -> None:
software_version: str, super().__init__(app_args['log_file'], **kwargs)
filename: str,
**kwargs) -> None:
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.rollover_info: Dict[str, str] = { self.rollover_info: Dict[str, str] = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}", 'header': f"{'-'*20}Moonraker Log Start{'-'*20}"
'version': f"Git Version: {software_version}",
} }
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] lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None: if self.stream is not None:
self.stream.write("\n".join(lines) + "\n") self.stream.write("\n".join(lines) + "\n")
@ -70,7 +69,7 @@ class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
self.rollover_info[name] = item self.rollover_info[name] = item
def doRollover(self) -> None: def doRollover(self) -> None:
super(MoonrakerLoggingHandler, self).doRollover() super().doRollover()
lines = [line for line in self.rollover_info.values() if line] lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None: if self.stream is not None:
self.stream.write("\n".join(lines) + "\n") self.stream.write("\n".join(lines) + "\n")
@ -107,8 +106,7 @@ def get_software_version() -> str:
version = "?" version = "?"
return version return version
def setup_logging(log_file: str, def setup_logging(app_args: Dict[str, Any]
software_version: str
) -> Tuple[logging.handlers.QueueListener, ) -> Tuple[logging.handlers.QueueListener,
Optional[MoonrakerLoggingHandler]]: Optional[MoonrakerLoggingHandler]]:
root_logger = logging.getLogger() root_logger = logging.getLogger()
@ -121,9 +119,9 @@ def setup_logging(log_file: str,
'[%(filename)s:%(funcName)s()] - %(message)s') '[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt) stdout_hdlr.setFormatter(stdout_fmt)
file_hdlr = None file_hdlr = None
if log_file: if app_args.get('log_file', ""):
file_hdlr = MoonrakerLoggingHandler( file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2) app_args, when='midnight', backupCount=2)
formatter = logging.Formatter( formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s') '%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter) file_hdlr.setFormatter(formatter)