diff --git a/config.conf b/config.conf index 1e0b54d..d06e2b1 100644 --- a/config.conf +++ b/config.conf @@ -4,6 +4,9 @@ wud.stadidisk.ru #Настройки необходимые для работы приложения [Settings] +# Источник списка: list или caddyfile +domainsSource=caddyfile + #Путь к файлу с логином/паролем для авторизации pathToCredentials=/etc/caddy-to-dsm/.secret diff --git a/service_functions.py b/service_functions.py index a80b90d..7e42b8f 100644 --- a/service_functions.py +++ b/service_functions.py @@ -6,6 +6,7 @@ from dataclasses import asdict import logging from configparser import ConfigParser from caddy_worker import CaddyWorker +import subprocess class ServiceFunctions: @@ -96,6 +97,101 @@ class ServiceFunctions: password=password, ) + @staticmethod + def get_caddy_proxy_domains(domain_suffix: str, settings: ApplSettings) -> list[str]: + """ + Получает список reverse_proxy-доменов с Cudy + через SSH и caddy adapt. + """ + + command = [ + "ssh", + "-T", + "-o", "BatchMode=yes", + "-o", "ConnectTimeout=5", + settings.ssh_host, + "/usr/bin/caddy adapt " + "--config /etc/caddy/Caddyfile " + "--adapter caddyfile" + ] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + timeout=30, + check=True + ) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as exc: + raise RuntimeError( + "Failed to read Caddyfile from Cudy" + ) from exc + + config = json.loads(result.stdout) + + servers = ( + config.get("apps", {}) + .get("http", {}) + .get("servers", {}) + ) + + def has_reverse_proxy(node): + if isinstance(node, dict): + if node.get("handler") == "reverse_proxy": + return True + return any( + has_reverse_proxy(value) + for value in node.values() + ) + + if isinstance(node, list): + return any( + has_reverse_proxy(item) + for item in node + ) + + return False + + suffix = domain_suffix.strip().lower().strip(".") + if not suffix: + raise ValueError("domainSuffix is empty") + + domains = set() + + for server in servers.values(): + for route in server.get("routes", []): + + if not has_reverse_proxy( + route.get("handle", []) + ): + continue + + for matcher in route.get("match", []): + for host in matcher.get("host", []): + host = host.lower().rstrip(".") + + if "*" in host: + continue + + if ( + host == suffix + or host.endswith("." + suffix) + ): + domains.add(host) + + if not domains: + raise RuntimeError( + "No reverse_proxy domains found in Caddyfile" + ) + + result_domains = sorted(domains) + + logging.info("Caddy proxy domains: %s",", ".join(result_domains)) + + return result_domains + def load_config(self): @@ -143,7 +239,39 @@ class ServiceFunctions: ) - domains = list(config["ListDomains"].keys()) + # Выбираем источник списка доменов + domains_source = config.get("Settings", "domainsSource", fallback="list").strip().lower() + + if domains_source == "caddyfile": + + domain_suffix = config.get( + "Settings", + "domainSuffix", + fallback="stadidisk.local" + ) + + domains = self.get_caddy_proxy_domains(domain_suffix) + + elif domains_source == "list": + + if not config.has_section("ListDomains"): + raise ValueError( + "Missing [ListDomains] section" + ) + + domains = list( + config["ListDomains"].keys() + ) + + else: + raise ValueError( + f"Unknown domainsSource: {domains_source}" + ) + + if not domains: + raise RuntimeError( + "Domain list is empty, synchronization aborted" + ) appl_settings = ApplSettings( list_domains = domains,