From b9a17e07e90214bc5c8b2b5da71ac3830ee97b48 Mon Sep 17 00:00:00 2001 From: Eric Callahan Date: Tue, 18 Oct 2022 08:06:56 -0400 Subject: [PATCH] moonraker: convert code to a package Signed-off-by: Eric Callahan --- moonraker/__init__.py | 5 ++ moonraker/__main__.py | 9 ++++ moonraker/app.py | 22 ++++---- moonraker/confighelper.py | 10 ++-- moonraker/klippy_connection.py | 18 +++---- moonraker/loghelper.py | 6 +-- moonraker/moonraker.py | 17 +++++++ moonraker/server.py | 92 +++++++++++++++++----------------- moonraker/websockets.py | 12 ++--- 9 files changed, 111 insertions(+), 80 deletions(-) create mode 100644 moonraker/__init__.py create mode 100644 moonraker/__main__.py create mode 100755 moonraker/moonraker.py diff --git a/moonraker/__init__.py b/moonraker/__init__.py new file mode 100644 index 0000000..c055a26 --- /dev/null +++ b/moonraker/__init__.py @@ -0,0 +1,5 @@ +# Top level package definition for Moonraker +# +# Copyright (C) 2022 Eric Callahan +# +# This file may be distributed under the terms of the GNU GPLv3 license diff --git a/moonraker/__main__.py b/moonraker/__main__.py new file mode 100644 index 0000000..25e6321 --- /dev/null +++ b/moonraker/__main__.py @@ -0,0 +1,9 @@ +# Package entry point for Moonraker +# +# Copyright (C) 2022 Eric Callahan +# +# This file may be distributed under the terms of the GNU GPLv3 license + +from .server import main + +main() diff --git a/moonraker/app.py b/moonraker/app.py index f4107a0..f3754a0 100644 --- a/moonraker/app.py +++ b/moonraker/app.py @@ -22,8 +22,8 @@ from tornado.escape import url_unescape, url_escape from tornado.routing import Rule, PathMatches, AnyMatches from tornado.http1connection import HTTP1Connection from tornado.log import access_log -from utils import ServerError -from websockets import ( +from .utils import ServerError +from .websockets import ( WebRequest, WebsocketManager, WebSocket, @@ -48,17 +48,17 @@ from typing import ( ) if TYPE_CHECKING: from tornado.httpserver import HTTPServer - from server import Server - from eventloop import EventLoop - from confighelper import ConfigHelper - from klippy_connection import KlippyConnection as Klippy - from components.file_manager.file_manager import FileManager - from components.announcements import Announcements - from components.machine import Machine + from .server import Server + from .eventloop import EventLoop + from .confighelper import ConfigHelper + from .klippy_connection import KlippyConnection as Klippy + from .components.file_manager.file_manager import FileManager + from .components.announcements import Announcements + from .components.machine import Machine from io import BufferedReader - import components.authorization + from .components.authorization import Authorization MessageDelgate = Optional[tornado.httputil.HTTPMessageDelegate] - AuthComp = Optional[components.authorization.Authorization] + AuthComp = Optional[Authorization] APICallback = Callable[[WebRequest], Coroutine] diff --git a/moonraker/confighelper.py b/moonraker/confighelper.py index bb5711a..012dd4f 100644 --- a/moonraker/confighelper.py +++ b/moonraker/confighelper.py @@ -14,8 +14,8 @@ import threading import copy import logging from io import StringIO -from utils import SentinelClass -from components.template import JinjaTemplate +from .utils import SentinelClass +from .components.template import JinjaTemplate # Annotation imports from typing import ( @@ -34,9 +34,9 @@ from typing import ( Type, ) if TYPE_CHECKING: - from server import Server - from components.gpio import GpioFactory, GpioOutputPin - from components.template import TemplateFactory + from .server import Server + from .components.gpio import GpioFactory, GpioOutputPin + from .components.template import TemplateFactory from io import TextIOWrapper _T = TypeVar("_T") ConfigVal = Union[None, int, float, bool, str, dict, list] diff --git a/moonraker/klippy_connection.py b/moonraker/klippy_connection.py index 79fc2fb..ff75b85 100644 --- a/moonraker/klippy_connection.py +++ b/moonraker/klippy_connection.py @@ -13,7 +13,7 @@ import json import getpass import asyncio import pathlib -from utils import ServerError, get_unix_peer_credentials +from .utils import ServerError, get_unix_peer_credentials # Annotation imports from typing import ( @@ -29,14 +29,14 @@ from typing import ( Tuple ) if TYPE_CHECKING: - from moonraker import Server - from app import MoonrakerApp - from websockets import WebRequest, Subscribable - from confighelper import ConfigHelper - from components.klippy_apis import KlippyAPI - from components.file_manager.file_manager import FileManager - from components.machine import Machine - from components.job_state import JobState + from .server import Server + from .app import MoonrakerApp + from .websockets import WebRequest, Subscribable + from .confighelper import ConfigHelper + from .components.klippy_apis import KlippyAPI + from .components.file_manager.file_manager import FileManager + from .components.machine import Machine + from .components.job_state import JobState FlexCallback = Callable[..., Optional[Coroutine]] # These endpoints are reserved for klippy/moonraker communication only and are diff --git a/moonraker/loghelper.py b/moonraker/loghelper.py index 7ed89a0..d3b49c0 100644 --- a/moonraker/loghelper.py +++ b/moonraker/loghelper.py @@ -23,9 +23,9 @@ from typing import ( ) if TYPE_CHECKING: - from moonraker import Server - from websockets import WebRequest - from klippy_connection import KlippyConnection + from .server import Server + from .websockets import WebRequest + from .klippy_connection import KlippyConnection # Coroutine friendly QueueHandler courtesy of Martjin Pieters: # https://www.zopatista.com/python/2019/05/11/asyncio-logging/ diff --git a/moonraker/moonraker.py b/moonraker/moonraker.py new file mode 100755 index 0000000..0948717 --- /dev/null +++ b/moonraker/moonraker.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +# Legacy entry point for Moonraker +# +# Copyright (C) 2022 Eric Callahan +# +# This file may be distributed under the terms of the GNU GPLv3 license + + +if __name__ == "__main__": + import sys + import importlib + import pathlib + pkg_parent = pathlib.Path(__file__).parent.parent + sys.path.pop(0) + sys.path.insert(0, str(pkg_parent)) + svr = importlib.import_module(".server", "moonraker") + svr.main(False) # type: ignore diff --git a/moonraker/server.py b/moonraker/server.py index 13340de..f8fa7dd 100755 --- a/moonraker/server.py +++ b/moonraker/server.py @@ -16,13 +16,13 @@ import time import socket import logging import signal -import confighelper import asyncio -from eventloop import EventLoop -from app import MoonrakerApp -from klippy_connection import KlippyConnection -from utils import ServerError, SentinelClass, get_software_version -from loghelper import LogManager +from . import confighelper +from .eventloop import EventLoop +from .app import MoonrakerApp +from .klippy_connection import KlippyConnection +from .utils import ServerError, SentinelClass, get_software_version +from .loghelper import LogManager # Annotation imports from typing import ( @@ -38,10 +38,10 @@ from typing import ( TypeVar, ) if TYPE_CHECKING: - from websockets import WebRequest, WebsocketManager - from components.file_manager.file_manager import FileManager - from components.machine import Machine - from components.extensions import ExtensionManager + from .websockets import WebRequest, WebsocketManager + from .components.file_manager.file_manager import FileManager + from .components.machine import Machine + from .components.extensions import ExtensionManager FlexCallback = Callable[..., Optional[Coroutine]] _T = TypeVar("_T") @@ -253,7 +253,8 @@ class Server: if component_name in self.components: return self.components[component_name] try: - module = importlib.import_module("components." + component_name) + full_name = f"moonraker.components.{component_name}" + module = importlib.import_module(full_name) is_core = component_name in CORE_COMPONENTS fallback: Optional[str] = "server" if is_core else None config = config.getsection(component_name, fallback) @@ -458,7 +459,38 @@ class Server: 'files': cfg_file_list } -def main(cmd_line_args: argparse.Namespace) -> None: +def main(from_package: bool = True) -> None: + # Parse start arguments + parser = argparse.ArgumentParser( + description="Moonraker - Klipper API Server") + parser.add_argument( + "-d", "--datapath", default=None, + metavar='', + help="Location of Moonraker Data File Path" + ) + parser.add_argument( + "-c", "--configfile", default=None, metavar='', + help="Location of moonraker configuration file") + parser.add_argument( + "-l", "--logfile", default=None, metavar='', + help="log file name and location") + parser.add_argument( + "-n", "--nologfile", action='store_true', + help="disable logging to a file") + parser.add_argument( + "-v", "--verbose", action="store_true", + help="Enable verbose logging" + ) + parser.add_argument( + "-g", "--debug", action="store_true", + help="Enable Moonraker debug features" + ) + parser.add_argument( + "-o", "--asyncio-debug", action="store_true", + help="Enable asyncio debug flag" + ) + cmd_line_args = parser.parse_args() + startup_warnings: List[str] = [] dp: str = cmd_line_args.datapath or "~/printer_data" data_path = pathlib.Path(dp).expanduser().resolve() @@ -481,7 +513,8 @@ def main(cmd_line_args: argparse.Namespace) -> None: "verbose": cmd_line_args.verbose, "debug": cmd_line_args.debug, "asyncio_debug": cmd_line_args.asyncio_debug, - "is_backup_config": False + "is_backup_config": False, + "is_python_package": from_package } # Setup Logging @@ -554,36 +587,3 @@ def main(cmd_line_args: argparse.Namespace) -> None: logging.info("Server Shutdown") log_manager.stop_logging() exit(estatus) - - -if __name__ == '__main__': - # Parse start arguments - parser = argparse.ArgumentParser( - description="Moonraker - Klipper API Server") - parser.add_argument( - "-d", "--datapath", default=None, - metavar='', - help="Location of Moonraker Data File Path" - ) - parser.add_argument( - "-c", "--configfile", default=None, metavar='', - help="Location of moonraker configuration file") - parser.add_argument( - "-l", "--logfile", default=None, metavar='', - help="log file name and location") - parser.add_argument( - "-n", "--nologfile", action='store_true', - help="disable logging to a file") - parser.add_argument( - "-v", "--verbose", action="store_true", - help="Enable verbose logging" - ) - parser.add_argument( - "-g", "--debug", action="store_true", - help="Enable Moonraker debug features" - ) - parser.add_argument( - "-o", "--asyncio-debug", action="store_true", - help="Enable asyncio debug flag" - ) - main(parser.parse_args()) diff --git a/moonraker/websockets.py b/moonraker/websockets.py index 6942110..fa055d7 100644 --- a/moonraker/websockets.py +++ b/moonraker/websockets.py @@ -12,7 +12,7 @@ import asyncio import copy from tornado.websocket import WebSocketHandler, WebSocketClosedError from tornado.web import HTTPError -from utils import ServerError, SentinelClass +from .utils import ServerError, SentinelClass # Annotation imports from typing import ( @@ -30,18 +30,18 @@ from typing import ( List, ) if TYPE_CHECKING: - from server import Server - from app import APIDefinition - from klippy_connection import KlippyConnection as Klippy + from .server import Server + from .app import APIDefinition + from .klippy_connection import KlippyConnection as Klippy from .components.extensions import ExtensionManager - import components.authorization + from .components.authorization import Authorization _T = TypeVar("_T") _C = TypeVar("_C", str, bool, float, int) IPUnion = Union[ipaddress.IPv4Address, ipaddress.IPv6Address] ConvType = Union[str, bool, float, int] ArgVal = Union[None, int, float, bool, str] RPCCallback = Callable[..., Coroutine] - AuthComp = Optional[components.authorization.Authorization] + AuthComp = Optional[Authorization] CLIENT_TYPES = ["web", "mobile", "desktop", "display", "bot", "agent", "other"] SENTINEL = SentinelClass.get_instance()