128 lines
4.3 KiB
Python
128 lines
4.3 KiB
Python
"""Entry point: load the configuration, then serve.
|
|
|
|
Startup is deliberately noisy about anything that will be hard to diagnose later:
|
|
warnings from configuration validation, the effective settings (with secrets
|
|
redacted), and any degraded optional feature. An OPDS server that is reachable
|
|
but shows an empty catalog should say why in its own log, not require a
|
|
debugging session.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import logging
|
|
import signal
|
|
import ssl
|
|
import sys
|
|
import threading
|
|
|
|
import app.server as app_server
|
|
from app import __version__
|
|
from app import config as app_config
|
|
|
|
LOGGER = logging.getLogger("app")
|
|
|
|
_LOG_FORMAT = "%(asctime)s %(levelname)-7s %(name)s: %(message)s"
|
|
_LOG_DATEFORMAT = "%Y-%m-%dT%H:%M:%S%z"
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(
|
|
prog="opds-from-rss",
|
|
description="Serve a FreshRSS account as an OPDS 1.2 catalog of EPUBs.",
|
|
)
|
|
parser.add_argument(
|
|
"--config",
|
|
metavar="PATH",
|
|
help="configuration file (default: $CONFIG_PATH, /config/config.json, config.json)",
|
|
)
|
|
parser.add_argument(
|
|
"--check-config",
|
|
action="store_true",
|
|
help="validate the configuration and print it, then exit",
|
|
)
|
|
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
return parser
|
|
|
|
|
|
def configure_logging(level: str) -> None:
|
|
logging.basicConfig(level=level.upper(), format=_LOG_FORMAT, datefmt=_LOG_DATEFORMAT)
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
arguments = build_parser().parse_args(argv)
|
|
# Logging is configured twice: once coarsely so a configuration failure is
|
|
# reported properly, then again at the level the configuration asks for.
|
|
configure_logging("info")
|
|
try:
|
|
settings = app_config.load_config(arguments.config)
|
|
except app_config.ConfigError as exc:
|
|
# The exception already lists every problem with its path.
|
|
print(str(exc), file=sys.stderr)
|
|
return 2
|
|
|
|
configure_logging(settings.server.log_level)
|
|
for warning in settings.warnings:
|
|
LOGGER.warning("configuration: %s", warning)
|
|
for line in app_config.describe_config(settings).splitlines():
|
|
LOGGER.info("%s", line)
|
|
|
|
if arguments.check_config:
|
|
LOGGER.info("configuration is valid; not starting the server")
|
|
return 0
|
|
|
|
httpd, application = app_server.build_server(settings)
|
|
if settings.server.tls_cert_file and settings.server.tls_key_file:
|
|
_enable_tls(httpd, settings.server.tls_cert_file, settings.server.tls_key_file)
|
|
LOGGER.info("serving HTTPS directly (no reverse proxy required)")
|
|
else:
|
|
LOGGER.warning(
|
|
"serving plain HTTP: put a TLS-terminating proxy in front of this, "
|
|
"because HTTP Basic credentials are only base64-encoded"
|
|
)
|
|
_install_signal_handlers(httpd)
|
|
|
|
LOGGER.info(
|
|
"listening on %s:%s; catalog at %s/opds",
|
|
settings.server.host,
|
|
settings.server.port,
|
|
settings.server.public_base_url or f"http://{settings.server.host}:{settings.server.port}",
|
|
)
|
|
try:
|
|
httpd.serve_forever(poll_interval=0.25)
|
|
finally:
|
|
LOGGER.info("shutting down")
|
|
httpd.server_close()
|
|
application.client.close()
|
|
return 0
|
|
|
|
|
|
def _enable_tls(httpd, cert_file: str, key_file: str) -> None:
|
|
"""Wrap the listening socket, so the service can be secure on its own.
|
|
|
|
The paths are passed in rather than read off the configuration so that the
|
|
"both or neither" guarantee made during validation is visible here too.
|
|
"""
|
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
context.load_cert_chain(cert_file, key_file)
|
|
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
|
|
|
|
|
|
def _install_signal_handlers(httpd) -> None:
|
|
"""Stop cleanly on SIGINT/SIGTERM, which is how a container is stopped.
|
|
|
|
``shutdown`` blocks until the serve loop exits and must not be called from the
|
|
thread running it, so the handler hands the work to a short-lived thread.
|
|
"""
|
|
|
|
def stop(signum: int, _frame: object) -> None:
|
|
LOGGER.info("received %s", signal.Signals(signum).name)
|
|
threading.Thread(target=httpd.shutdown, daemon=True).start()
|
|
|
|
for handled in (signal.SIGINT, signal.SIGTERM):
|
|
signal.signal(handled, stop)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|