mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
feat(serve): add operator dashboard endpoints and per-key rate limits
This commit is contained in:
@@ -15,7 +15,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from unshackle.core.api.events import bus
|
||||
from unshackle.core.api.events import bus, publish_service_event
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_text
|
||||
|
||||
@@ -741,6 +741,7 @@ class DownloadQueueManager:
|
||||
applied = await asyncio.to_thread(services.apply_pending, self.busy_services())
|
||||
if applied:
|
||||
log.info(f"Services reloaded after job completion: {', '.join(applied)}")
|
||||
publish_service_event("applied", applied)
|
||||
except Exception:
|
||||
log.exception("Applying pending service reloads failed")
|
||||
|
||||
|
||||
@@ -54,3 +54,34 @@ def _put_drop(queue: asyncio.Queue, item: Dict[str, Any]) -> None:
|
||||
|
||||
|
||||
bus = EventBus()
|
||||
|
||||
|
||||
def publish_service_event(action: str, tags: List[str], errors: Optional[List[str]] = None) -> None:
|
||||
"""Tell dashboard listeners that services were staged, applied, or failed to reload.
|
||||
|
||||
Lives here rather than in ``core.services`` so the service loader never imports the API layer.
|
||||
"""
|
||||
data: Dict[str, Any] = {"action": action, "tags": list(tags)}
|
||||
if errors:
|
||||
data["errors"] = list(errors)
|
||||
bus.publish("service", data)
|
||||
|
||||
|
||||
def publish_refresh_events(repos: List[Dict[str, Any]]) -> None:
|
||||
"""Publish the ``service`` events one ``refresh_and_reload`` result implies.
|
||||
|
||||
A tag counts as applied only when it changed, was not deferred, and did not fail to
|
||||
import - a failed re-import keeps the old module, so calling it applied would be a lie.
|
||||
"""
|
||||
from unshackle.core.services import failed_tags
|
||||
|
||||
for repo in repos:
|
||||
failed = failed_tags(repo["load_errors"])
|
||||
changed = {line[1:] for line in repo["changes"] if line and line[0] in "+~-!"}
|
||||
applied = sorted(changed - set(repo["deferred"]) - failed)
|
||||
if applied:
|
||||
publish_service_event("applied", applied)
|
||||
if repo["deferred"]:
|
||||
publish_service_event("staged", repo["deferred"])
|
||||
if repo["load_errors"]:
|
||||
publish_service_event("failed", [], errors=repo["load_errors"])
|
||||
|
||||
+347
-14
@@ -4,9 +4,11 @@ import enum
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import Counter
|
||||
from datetime import date as date_
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, Iterable, List, Optional
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
@@ -275,10 +277,10 @@ def setup_list_service(
|
||||
return service_instance
|
||||
|
||||
|
||||
def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List[str]]:
|
||||
"""Get effective service allowlist considering global + per-key config.
|
||||
def allowed_services_for_key(secret_key: Optional[str]) -> Optional[List[str]]:
|
||||
"""Effective service allowlist for an API key: the global list intersected with the key's.
|
||||
|
||||
Returns None if no allowlist restricts the services.
|
||||
Returns None when nothing restricts the services.
|
||||
"""
|
||||
global_allowed = config.serve.get("services")
|
||||
global_set: Optional[set[str]] = None
|
||||
@@ -286,14 +288,11 @@ def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List
|
||||
global_set = {Services.get_tag(s) for s in global_allowed}
|
||||
|
||||
key_set: Optional[set[str]] = None
|
||||
if request:
|
||||
secret_key = request_secret_key(request)
|
||||
if secret_key:
|
||||
users = config.serve.get("users", {})
|
||||
user_config = users.get(secret_key, {})
|
||||
user_services = user_config.get("services")
|
||||
if user_services:
|
||||
key_set = {Services.get_tag(s) for s in user_services}
|
||||
if secret_key:
|
||||
users = config.serve.get("users", {})
|
||||
user_config = users.get(secret_key, {})
|
||||
if isinstance(user_config, dict) and user_config.get("services"):
|
||||
key_set = {Services.get_tag(s) for s in user_config["services"]}
|
||||
|
||||
if global_set and key_set:
|
||||
result = global_set & key_set
|
||||
@@ -307,6 +306,11 @@ def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List
|
||||
return list(result)
|
||||
|
||||
|
||||
def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List[str]]:
|
||||
"""The effective service allowlist for a request's API key, or None when unrestricted."""
|
||||
return allowed_services_for_key(request_secret_key(request) if request else None)
|
||||
|
||||
|
||||
def server_cdm_allowed(request: Optional[web.Request] = None, service: Optional[str] = None) -> bool:
|
||||
"""Whether the calling API key may have the server operate the CDM licensing for ``service``.
|
||||
|
||||
@@ -551,6 +555,45 @@ async def dashboard_authentication(request: web.Request, handler: Any) -> web.St
|
||||
return await handler(request)
|
||||
|
||||
|
||||
def rate_limit_response(secret_key: str) -> Optional[web.Response]:
|
||||
"""A 429 when *secret_key* is over its hourly limit, else None after counting the request.
|
||||
|
||||
Call only once the key is known to be valid, so an invalid key cannot burn someone else's
|
||||
window. Both auth middlewares go through here: the limit has to hold in every server mode.
|
||||
"""
|
||||
from unshackle.core.api.stats import stats
|
||||
|
||||
retry_after = stats.check_rate_limit(secret_key)
|
||||
if retry_after is None:
|
||||
return None
|
||||
return web.json_response(
|
||||
{"status": 429, "message": "Rate limit exceeded."},
|
||||
status=429,
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
)
|
||||
|
||||
|
||||
@web.middleware
|
||||
async def api_key_authentication(request: web.Request, handler: Any) -> web.StreamResponse:
|
||||
"""Gate every non-dashboard route behind a key in ``app["config"]["users"]``, then rate limit it.
|
||||
|
||||
Runs after :func:`dashboard_authentication`, which has already answered the dashboard
|
||||
routes, so the dashboard key never reaches the limiter.
|
||||
"""
|
||||
import hmac
|
||||
|
||||
if request.path == "/api/health" or request.path.startswith(DASHBOARD_PREFIX):
|
||||
return await handler(request)
|
||||
secret_key = request_secret_key(request)
|
||||
if not secret_key:
|
||||
return web.json_response({"status": 401, "message": "Secret Key is Empty."}, status=401)
|
||||
# Constant-time compare against every configured key so a valid key can't be
|
||||
# recovered byte-by-byte from response timing.
|
||||
if not any(hmac.compare_digest(secret_key, k) for k in request.app["config"]["users"]):
|
||||
return web.json_response({"status": 401, "message": "Secret Key is Invalid."}, status=401)
|
||||
return rate_limit_response(secret_key) or await handler(request)
|
||||
|
||||
|
||||
def caller_key(request: Optional[web.Request] = None) -> str:
|
||||
"""The authenticating API key for a request, or 'anonymous' when unauthenticated."""
|
||||
if not request:
|
||||
@@ -1744,8 +1787,6 @@ async def download_job_events_handler(job_id: str, request: web.Request) -> web.
|
||||
|
||||
async def dashboard_status_handler(request: web.Request) -> web.Response:
|
||||
"""Server-wide stats for the developer dashboard."""
|
||||
from collections import Counter
|
||||
|
||||
from unshackle.core.api.download_manager import get_download_manager
|
||||
from unshackle.core.api.session_store import get_session_store
|
||||
from unshackle.core.api.stats import stats
|
||||
@@ -1790,6 +1831,296 @@ async def dashboard_logs_handler(request: web.Request) -> web.Response:
|
||||
return web.json_response({"seq": ring.seq, "records": records})
|
||||
|
||||
|
||||
async def dashboard_session_logs_handler(request: web.Request) -> web.Response:
|
||||
"""One remote session's mirrored service log, for an operator watching a failing auth.
|
||||
|
||||
Reads through ``peek``: a dashboard poll must not refresh the session's idle timer, and
|
||||
``SessionLogBuffer.since`` is a cursor read, so this never takes records from the client
|
||||
draining the same buffer through ``/api/session/{id}/logs``.
|
||||
"""
|
||||
from unshackle.core.api.session_store import get_session_store
|
||||
|
||||
session_id = request.match_info["session_id"]
|
||||
session = get_session_store().peek(session_id)
|
||||
if session is None:
|
||||
raise APIError(APIErrorCode.SESSION_NOT_FOUND, f"Remote session not found: {session_id}")
|
||||
try:
|
||||
since = int(request.query.get("since", 0))
|
||||
except ValueError:
|
||||
since = 0
|
||||
buffer = session.log_buffer
|
||||
return web.json_response(
|
||||
{
|
||||
"session_id": session_id,
|
||||
"records": buffer.since(since) if buffer else [],
|
||||
"last_seq": buffer.last_seq if buffer else 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def dashboard_keys_handler(request: web.Request) -> web.Response:
|
||||
"""Every configured API key: which key it is, what it may do, and what it has done.
|
||||
|
||||
Every key that ``configured_key`` counts gets a row here, so each ``requests_by_key``
|
||||
bucket except ``anonymous`` has a row to attribute it to. Without the dashboard key's own
|
||||
row, a dashboard would render its own polling as traffic from an unknown caller.
|
||||
"""
|
||||
from unshackle.core.api.stats import key_id, key_rate_limit, key_tier, mask_key, stats
|
||||
|
||||
users = config.serve.get("users") or {}
|
||||
api_secret = str(config.serve.get("api_secret") or "")
|
||||
dashboard = dashboard_key() or ""
|
||||
|
||||
def row(secret_key: str, role: str) -> Dict[str, Any]:
|
||||
entry = stats.keys.get(key_id(secret_key))
|
||||
api_access = role != "dashboard" or secret_key in users
|
||||
return {
|
||||
"id": key_id(secret_key),
|
||||
"role": role,
|
||||
"label": mask_key(secret_key),
|
||||
"services": allowed_services_for_key(secret_key) if api_access else [],
|
||||
"server_cdm": user_grant(secret_key, "server_cdm") if api_access else False,
|
||||
"server_accounts": user_grant(secret_key, "server_accounts") if api_access else False,
|
||||
"server_proxy": user_grant(secret_key, "server_proxy") is True if api_access else False,
|
||||
"tier": key_tier(secret_key),
|
||||
"rate_limit": key_rate_limit(secret_key),
|
||||
"window_used": entry.window_used if entry else 0,
|
||||
"requests": entry.requests if entry else 0,
|
||||
"rejected": entry.rejected if entry else 0,
|
||||
"bytes_out": entry.bytes_out if entry else 0,
|
||||
"last_seen": entry.last_seen if entry else None,
|
||||
}
|
||||
|
||||
def role_of(secret_key: str) -> str:
|
||||
"""Which key this is. Identity, not capability: the grant fields carry that."""
|
||||
if dashboard and secret_key == dashboard:
|
||||
return "dashboard"
|
||||
return "admin" if secret_key == api_secret else "user"
|
||||
|
||||
keys = [str(k) for k in users]
|
||||
for extra in (api_secret, dashboard):
|
||||
if extra and extra not in keys:
|
||||
keys.append(extra)
|
||||
return web.json_response([row(k, role_of(k)) for k in keys])
|
||||
|
||||
|
||||
def user_grant(secret_key: str, name: str) -> Any:
|
||||
"""A per-key grant as configured: False, True, or the list of service tags it covers.
|
||||
|
||||
A key with no ``serve.users`` entry keeps implicit access, matching the resolvers.
|
||||
"""
|
||||
user_config = (config.serve.get("users") or {}).get(secret_key)
|
||||
if not isinstance(user_config, dict):
|
||||
return name != "server_proxy"
|
||||
return user_config.get(name, False)
|
||||
|
||||
|
||||
async def dashboard_services_handler(request: web.Request) -> web.Response:
|
||||
"""Every discovered service and its load state, including the ones that failed to import.
|
||||
|
||||
Not allowlist-filtered: an operator needs to see the services their keys cannot reach.
|
||||
"""
|
||||
from unshackle.core import services as services_module
|
||||
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
|
||||
from unshackle.core.api.session_store import get_session_store
|
||||
from unshackle.core.service_repo import head
|
||||
|
||||
sessions = Counter(entry.service_tag for entry in get_session_store().list())
|
||||
jobs = Counter(job.service for job in get_download_manager().list_jobs() if job.status not in TERMINAL_STATUSES)
|
||||
errors = {err.split(":", 1)[0]: err for err in services_module.LOAD_ERRORS if ":" in err}
|
||||
staged_commits: Dict[Any, Optional[str]] = {}
|
||||
|
||||
rows = []
|
||||
for tag in Services.get_tags():
|
||||
error = errors.get(tag)
|
||||
staged = tag in services_module.PENDING
|
||||
row: Dict[str, Any] = {
|
||||
"tag": tag,
|
||||
"state": "failed" if error else "staged" if staged else "loaded",
|
||||
"error": error,
|
||||
"commit": services_module.LOADED_COMMITS.get(tag),
|
||||
"staged_commit": None,
|
||||
"staged_since": services_module.PENDING_SINCE.get(tag),
|
||||
"sessions": sessions.get(tag, 0),
|
||||
"jobs": jobs.get(tag, 0),
|
||||
"aliases": list(services_module.ALIASES.get(tag, ())),
|
||||
"geofence": [],
|
||||
}
|
||||
if staged:
|
||||
# Only staged tags need a git call; the working tree already holds the new commit.
|
||||
source = services_module.service_source_dir(tag)
|
||||
if source is not None and source not in staged_commits:
|
||||
staged_commits[source] = head(source) if (source / ".git").exists() else None
|
||||
row["staged_commit"] = staged_commits.get(source)
|
||||
module = services_module.MODULES.get(tag)
|
||||
if module is not None:
|
||||
row["geofence"] = list(getattr(module, "GEOFENCE", ()) or ())
|
||||
rows.append(row)
|
||||
return web.json_response(rows)
|
||||
|
||||
|
||||
HEALTH_CACHE_TTL = 30.0
|
||||
HEALTH_PROBE_KID = "00000000000000000000000000000000"
|
||||
HEALTH_DETAIL_MAX = 256
|
||||
HEALTH_PROBE_TIMEOUT = 15.0
|
||||
HEALTH_SECRET_MIN = 4
|
||||
SECRET_KEYS = ("password", "passwd", "pwd", "token", "api_key", "apikey", "secret", "auth", "ssl_key_password")
|
||||
_health_cache: Dict[str, Any] = {}
|
||||
_health_lock: Optional[asyncio.Lock] = None
|
||||
|
||||
|
||||
async def dashboard_health_handler(request: web.Request) -> web.Response:
|
||||
"""Preflight: can this instance actually finish a download?
|
||||
|
||||
A panel, not a liveness probe - the result is cached for 30 s and every probe is shallow,
|
||||
so reading it never costs the operator a proxy session or a licence.
|
||||
"""
|
||||
global _health_lock
|
||||
if _health_lock is None:
|
||||
_health_lock = asyncio.Lock()
|
||||
async with _health_lock:
|
||||
now = time.time()
|
||||
cached = _health_cache.get("payload")
|
||||
if cached and now - _health_cache.get("at", 0.0) < HEALTH_CACHE_TTL:
|
||||
return web.json_response(cached)
|
||||
|
||||
checks: List[Dict[str, Any]] = []
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.to_thread(run_health_checks, checks), HEALTH_PROBE_TIMEOUT)
|
||||
except asyncio.TimeoutError:
|
||||
checks = list(checks)
|
||||
checks.append(
|
||||
{
|
||||
"id": "probe",
|
||||
"label": "health probe",
|
||||
"status": "fail",
|
||||
"detail": f"timed out after {HEALTH_PROBE_TIMEOUT:.0f}s with {len(checks)} checks done",
|
||||
"ms": round(HEALTH_PROBE_TIMEOUT * 1000, 1),
|
||||
}
|
||||
)
|
||||
statuses = {c["status"] for c in checks}
|
||||
payload = {
|
||||
"generated_at": now,
|
||||
"status": "failing" if "fail" in statuses else "degraded" if "warn" in statuses else "ok",
|
||||
"checks": checks,
|
||||
}
|
||||
_health_cache.update(at=now, payload=payload)
|
||||
return web.json_response(payload)
|
||||
|
||||
|
||||
def config_secrets(section: Any, nested: bool = False) -> List[str]:
|
||||
"""Values in a vault or proxy config that must never reach a health detail.
|
||||
|
||||
Name-based at the top level, and every scalar below it: a nested mapping is driver
|
||||
arguments unshackle cannot name in advance (an API vault's ``headers``, a MySQL vault's
|
||||
``ssl``, a proxy provider's own block), so it over-collects there on purpose. Short values
|
||||
are skipped, because masking them would garble the detail without hiding anything.
|
||||
"""
|
||||
if isinstance(section, dict):
|
||||
items: Iterable[tuple[Any, Any]] = section.items()
|
||||
elif isinstance(section, (list, tuple)):
|
||||
items = [(None, value) for value in section]
|
||||
else:
|
||||
return [str(section)] if nested and section is not None else []
|
||||
|
||||
found: List[str] = []
|
||||
for key, value in items:
|
||||
if isinstance(value, (dict, list, tuple)):
|
||||
found += config_secrets(value, nested=True)
|
||||
elif value is not None and (nested or (isinstance(key, str) and key.lower() in SECRET_KEYS)):
|
||||
found.append(str(value))
|
||||
return [secret for secret in found if len(secret) >= HEALTH_SECRET_MIN]
|
||||
|
||||
|
||||
def health_check(check_id: str, label: str, probe: Any, secrets: Iterable[str] = ()) -> Dict[str, Any]:
|
||||
"""Time one health probe and turn any exception into a failed check.
|
||||
|
||||
*secrets* are masked out of the detail: a driver's error string can echo the DSN or URL
|
||||
it was given. The detail is then capped, because redaction only hides what it recognises
|
||||
and a driver can raise with a whole response body inside it. Cap after masking, never
|
||||
before: a cut through a secret would leave the tail of it unreplaced.
|
||||
"""
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
status, detail = probe()
|
||||
except Exception as e:
|
||||
status, detail = "fail", f"{type(e).__name__}: {e}"
|
||||
masked = redact_text(detail, secrets) or ""
|
||||
if len(masked) > HEALTH_DETAIL_MAX:
|
||||
masked = masked[:HEALTH_DETAIL_MAX] + "…"
|
||||
return {
|
||||
"id": check_id,
|
||||
"label": label,
|
||||
"status": status,
|
||||
"detail": masked,
|
||||
"ms": round((time.perf_counter() - started) * 1000, 1),
|
||||
}
|
||||
|
||||
|
||||
def run_health_checks(checks: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]]:
|
||||
"""Probe binaries, CDM devices, key vaults and proxy providers. Blocking; run in a thread.
|
||||
|
||||
Appends to *checks* as each probe finishes rather than returning only at the end, so a
|
||||
caller that gives up on the deadline still has the results that did complete.
|
||||
"""
|
||||
from unshackle.commands.env import get_dependencies
|
||||
from unshackle.core.proxies.resolve import initialize_proxy_providers
|
||||
|
||||
if checks is None:
|
||||
checks = []
|
||||
|
||||
for dep in (d for d in get_dependencies() if d["cat"] != "Player"):
|
||||
binary = dep["binary"]
|
||||
|
||||
def probe(binary: Any = binary, dep: Any = dep) -> tuple[str, str]:
|
||||
if not binary:
|
||||
return ("fail" if dep["required"] else "warn", "not found on PATH")
|
||||
version = binary_version(binary) or "unknown version"
|
||||
return "ok", f"{version} · {binary}"
|
||||
|
||||
checks.append(health_check(dep["name"].lower(), dep["name"], probe))
|
||||
|
||||
def cdm_probe() -> tuple[str, str]:
|
||||
wvds = list(config.directories.wvds.glob("*.wvd"))
|
||||
prds = list(config.directories.prds.glob("*.prd"))
|
||||
if not wvds and not prds:
|
||||
return ("fail" if config.cdm else "warn", "no .wvd or .prd device files found")
|
||||
return "ok", f"{len(wvds)} Widevine, {len(prds)} PlayReady"
|
||||
|
||||
checks.append(health_check("cdm", "CDM devices", cdm_probe))
|
||||
|
||||
probe_service = next(iter(Services.get_tags()), "health")
|
||||
for vault_config in config.key_vaults or []:
|
||||
name = vault_config.get("name") or vault_config.get("type", "vault")
|
||||
|
||||
def vault_probe(vault_config: Any = vault_config) -> tuple[str, str]:
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
cfg = dict(vault_config)
|
||||
vaults = Vaults(probe_service)
|
||||
vaults.load_critical(cfg.pop("type"), **cfg)
|
||||
vault = vaults.vaults[0]
|
||||
try:
|
||||
vault.get_key(HEALTH_PROBE_KID, probe_service)
|
||||
except Exception as e:
|
||||
if type(e).__name__ not in ("KeyIdInvalid", "ServiceTagInvalid"):
|
||||
raise
|
||||
return "ok", str(vault)
|
||||
|
||||
checks.append(health_check(f"vault:{name}", f"vault {name}", vault_probe, config_secrets(vault_config)))
|
||||
|
||||
def proxy_probe() -> tuple[str, str]:
|
||||
providers = initialize_proxy_providers(raise_errors=True, quiet=True)
|
||||
if not providers:
|
||||
return "ok", "none configured"
|
||||
return "ok", ", ".join(type(p).__name__ for p in providers)
|
||||
|
||||
if config.proxy_providers:
|
||||
checks.append(health_check("proxies", "proxy providers", proxy_probe, config_secrets(config.proxy_providers)))
|
||||
|
||||
return checks
|
||||
|
||||
|
||||
async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
|
||||
"""Server-wide SSE event stream: `log`, `session` and `job` events, plus `stats` every 5 s (also the keep-alive).
|
||||
|
||||
@@ -2218,11 +2549,13 @@ async def clear_temp_handler(request: Optional[web.Request] = None) -> web.Respo
|
||||
async def refresh_services_handler(request: Optional[web.Request] = None) -> web.Response:
|
||||
"""Refresh the service repos configured in directories.services and reload the changed services."""
|
||||
from unshackle.core.api.download_manager import get_download_manager
|
||||
from unshackle.core.api.events import publish_refresh_events
|
||||
from unshackle.core.services import refresh_and_reload
|
||||
|
||||
try:
|
||||
busy = get_download_manager().busy_services()
|
||||
repos = await asyncio.to_thread(refresh_and_reload, busy)
|
||||
publish_refresh_events(repos)
|
||||
return web.json_response({"refreshed": all(r["updated"] for r in repos), "repos": repos})
|
||||
|
||||
except APIError:
|
||||
|
||||
@@ -21,8 +21,12 @@ from unshackle.core.api.handlers import (
|
||||
clear_finished_download_jobs_handler,
|
||||
clear_temp_handler,
|
||||
dashboard_events_handler,
|
||||
dashboard_health_handler,
|
||||
dashboard_jobs_handler,
|
||||
dashboard_keys_handler,
|
||||
dashboard_logs_handler,
|
||||
dashboard_services_handler,
|
||||
dashboard_session_logs_handler,
|
||||
dashboard_sessions_handler,
|
||||
dashboard_status_handler,
|
||||
delete_history_handler,
|
||||
@@ -2123,6 +2127,249 @@ async def dashboard_logs(request: web.Request) -> web.Response:
|
||||
return await dashboard_logs_handler(request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def dashboard_session_logs(request: web.Request) -> web.Response:
|
||||
"""
|
||||
Dashboard: one remote session's service log.
|
||||
---
|
||||
summary: Dashboard remote session log
|
||||
description: >
|
||||
The service's own log output for a remote session, mirrored at INFO regardless of the
|
||||
server's log level. This is where the real reason for a failed authentication sits, in
|
||||
full, while the session summary carries only a truncated `auth_error`.
|
||||
Reading this does not refresh the session's idle timer and does not take records from
|
||||
the client draining the same buffer through `/api/session/{session_id}/logs`.
|
||||
Poll when the session summary's `log_seq` changes.
|
||||
tags: [Dashboard]
|
||||
parameters:
|
||||
- name: session_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
- name: since
|
||||
in: query
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
description: Return only records with seq greater than this value
|
||||
responses:
|
||||
'200':
|
||||
description: Log records plus the buffer's current last_seq
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
session_id:
|
||||
type: string
|
||||
last_seq:
|
||||
type: integer
|
||||
records:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
seq:
|
||||
type: integer
|
||||
ts:
|
||||
type: number
|
||||
level:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
'401':
|
||||
description: Dashboard key missing or invalid
|
||||
'404':
|
||||
description: Remote session not found
|
||||
"""
|
||||
return await dashboard_session_logs_handler(request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def dashboard_keys(request: web.Request) -> web.Response:
|
||||
"""
|
||||
Dashboard: configured API keys, their grants and their usage.
|
||||
---
|
||||
summary: Dashboard API keys
|
||||
description: >
|
||||
Every key in `serve.users`, plus `serve.api_secret` and the dashboard key when they are
|
||||
configured, with the grants that decide what it may do and the counters for what it has
|
||||
done. A key listed in more than one of those places still gets exactly one row.
|
||||
`id` is a hash prefix, stable across restarts and carrying no key material, so two
|
||||
unnamed keys never merge the way they do in the `requests_by_key` labels.
|
||||
Every key the server counts has a row here, so a `requests_by_key` bucket other than
|
||||
`anonymous` always matches one.
|
||||
`bytes_out` counts response bodies only: an SSE stream reports no content length and
|
||||
contributes nothing.
|
||||
tags: [Dashboard]
|
||||
responses:
|
||||
'200':
|
||||
description: One row per configured key
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
enum: [user, admin, dashboard]
|
||||
description: >
|
||||
Which key this is, not what it may do: `admin` is `serve.api_secret`,
|
||||
`dashboard` is `serve.dashboard.key`. The grant fields carry capability.
|
||||
label:
|
||||
type: string
|
||||
services:
|
||||
type: array
|
||||
nullable: true
|
||||
items:
|
||||
type: string
|
||||
description: >
|
||||
Effective allowlist; null when nothing restricts the key, and an empty
|
||||
list when the key reaches no service route at all, as a dashboard key
|
||||
with no `serve.users` entry does
|
||||
server_cdm:
|
||||
description: false, true, or the list of service tags it covers
|
||||
server_accounts:
|
||||
description: false, true, or the list of service tags it covers
|
||||
server_proxy:
|
||||
type: boolean
|
||||
tier:
|
||||
type: string
|
||||
nullable: true
|
||||
rate_limit:
|
||||
type: integer
|
||||
nullable: true
|
||||
description: Requests per hour; null means unlimited
|
||||
window_used:
|
||||
type: integer
|
||||
requests:
|
||||
type: integer
|
||||
rejected:
|
||||
type: integer
|
||||
bytes_out:
|
||||
type: integer
|
||||
last_seen:
|
||||
type: number
|
||||
nullable: true
|
||||
'401':
|
||||
description: Dashboard key missing or invalid
|
||||
"""
|
||||
return await dashboard_keys_handler(request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def dashboard_services(request: web.Request) -> web.Response:
|
||||
"""
|
||||
Dashboard: every discovered service and its load state.
|
||||
---
|
||||
summary: Dashboard services
|
||||
description: >
|
||||
Unlike `/api/services` this is not filtered by any allowlist and it keeps the services
|
||||
that failed to import, with their error. `state` is `loaded`, `staged` (an update is on
|
||||
disk but a busy service blocks the re-import) or `failed`.
|
||||
A staged service applies when its last job finishes; watch the `service` event on
|
||||
`/api/dashboard/events` instead of polling for it.
|
||||
tags: [Dashboard]
|
||||
responses:
|
||||
'200':
|
||||
description: One row per discovered service
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
tag:
|
||||
type: string
|
||||
state:
|
||||
type: string
|
||||
enum: [loaded, staged, failed]
|
||||
error:
|
||||
type: string
|
||||
nullable: true
|
||||
commit:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Repo HEAD the loaded code was imported from
|
||||
staged_commit:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Repo HEAD waiting to be imported; only set while staged
|
||||
staged_since:
|
||||
type: number
|
||||
nullable: true
|
||||
sessions:
|
||||
type: integer
|
||||
jobs:
|
||||
type: integer
|
||||
aliases:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
geofence:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
'401':
|
||||
description: Dashboard key missing or invalid
|
||||
"""
|
||||
return await dashboard_services_handler(request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def dashboard_health(request: web.Request) -> web.Response:
|
||||
"""
|
||||
Dashboard: preflight checks.
|
||||
---
|
||||
summary: Dashboard health preflight
|
||||
description: >
|
||||
Whether this instance could actually finish a download: the binaries on PATH, the CDM
|
||||
device files, each configured key vault and the proxy providers.
|
||||
A panel, not a liveness probe. The result is cached for 30 seconds and every probe is
|
||||
shallow, so reading it never spends a proxy session or a licence. A provider that only
|
||||
fails on first use is therefore not caught here.
|
||||
tags: [Dashboard]
|
||||
responses:
|
||||
'200':
|
||||
description: Roll-up status plus one entry per check
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
generated_at:
|
||||
type: number
|
||||
status:
|
||||
type: string
|
||||
enum: [ok, degraded, failing]
|
||||
checks:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
label:
|
||||
type: string
|
||||
status:
|
||||
type: string
|
||||
enum: [ok, warn, fail]
|
||||
detail:
|
||||
type: string
|
||||
ms:
|
||||
type: number
|
||||
'401':
|
||||
description: Dashboard key missing or invalid
|
||||
"""
|
||||
return await dashboard_health_handler(request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def dashboard_events(request: web.Request) -> web.StreamResponse:
|
||||
"""
|
||||
@@ -2201,6 +2448,10 @@ DASHBOARD_ROUTES: list[tuple[str, str, Handler, bool]] = [
|
||||
("GET", DASHBOARD_PREFIX + "sessions", dashboard_sessions, True),
|
||||
("GET", DASHBOARD_PREFIX + "jobs", dashboard_jobs, True),
|
||||
("GET", DASHBOARD_PREFIX + "logs", dashboard_logs, True),
|
||||
("GET", DASHBOARD_PREFIX + "keys", dashboard_keys, True),
|
||||
("GET", DASHBOARD_PREFIX + "services", dashboard_services, True),
|
||||
("GET", DASHBOARD_PREFIX + "health", dashboard_health, True),
|
||||
("GET", DASHBOARD_PREFIX + "sessions/{session_id}/logs", dashboard_session_logs, True),
|
||||
("GET", DASHBOARD_EVENTS_ROUTE, dashboard_events, True),
|
||||
]
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ class SessionEntry:
|
||||
"auth_status": self.auth_status.value,
|
||||
"auth_error": self.auth_error,
|
||||
"server_account": self.server_account,
|
||||
"log_seq": self.log_buffer.last_seq if self.log_buffer else 0,
|
||||
"client": self.client,
|
||||
"actions": list(self.actions),
|
||||
"created_at": self.created_at.isoformat(),
|
||||
@@ -103,9 +104,14 @@ class SessionStore:
|
||||
return config.serve.get("session_ttl", 300)
|
||||
|
||||
@property
|
||||
def max_sessions(self) -> int:
|
||||
"""Max concurrent sessions from config."""
|
||||
return config.serve.get("max_sessions", 100)
|
||||
def max_sessions(self) -> Optional[int]:
|
||||
"""Max concurrent sessions from config; None when the operator set no limit.
|
||||
|
||||
``max_sessions: null`` or ``0`` means unlimited, so a dashboard can tell "no cap" from
|
||||
a cap that happens to sit at the default.
|
||||
"""
|
||||
limit = config.serve.get("max_sessions", 100)
|
||||
return limit if isinstance(limit, int) and limit > 0 else None
|
||||
|
||||
async def create(
|
||||
self,
|
||||
@@ -118,9 +124,10 @@ class SessionStore:
|
||||
) -> SessionEntry:
|
||||
"""Make a new remote session with an authenticated service instance."""
|
||||
async with self._lock:
|
||||
if len(self._sessions) >= self.max_sessions:
|
||||
max_sessions = self.max_sessions
|
||||
if max_sessions is not None and len(self._sessions) >= max_sessions:
|
||||
oldest_id = min(self._sessions, key=lambda k: self._sessions[k].last_accessed)
|
||||
log.warning(f"Max sessions reached ({self.max_sessions}), evicting oldest: {oldest_id}")
|
||||
log.warning(f"Max sessions reached ({max_sessions}), evicting oldest: {oldest_id}")
|
||||
_publish("delete", self._sessions.pop(oldest_id), "evicted")
|
||||
|
||||
session_id = session_id or str(uuid.uuid4())
|
||||
@@ -154,6 +161,14 @@ class SessionStore:
|
||||
entry.touch()
|
||||
return entry
|
||||
|
||||
def peek(self, session_id: str) -> Optional[SessionEntry]:
|
||||
"""A session entry without touching it, for read-only observers.
|
||||
|
||||
``get`` refreshes ``last_accessed`` and expires stale entries, so an observer polling
|
||||
through it would keep an idle session alive and always report it as active.
|
||||
"""
|
||||
return self._sessions.get(session_id)
|
||||
|
||||
async def delete(self, session_id: str) -> bool:
|
||||
"""Delete a remote session. Returns True if it existed."""
|
||||
async with self._lock:
|
||||
|
||||
+132
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import time
|
||||
from collections import Counter, deque
|
||||
@@ -14,17 +15,101 @@ from unshackle.core import __code_hash__, __version__
|
||||
from unshackle.core.api.events import bus
|
||||
from unshackle.core.config import config
|
||||
|
||||
RATE_LIMIT_WINDOW = 3600.0
|
||||
|
||||
|
||||
def _users() -> Dict[str, Any]:
|
||||
users = (config.serve or {}).get("users")
|
||||
return users if isinstance(users, dict) else {}
|
||||
|
||||
|
||||
def _user_config(key: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
user = _users().get(key) if key else None
|
||||
return user if isinstance(user, dict) else None
|
||||
|
||||
|
||||
def configured_key(key: Optional[str]) -> Optional[str]:
|
||||
"""*key* when the config knows it (a user key, the master secret or the dashboard key), else None.
|
||||
|
||||
Open routes answer 200 to any header value, so attributing by the raw header would let an
|
||||
unauthenticated caller grow ``stats.keys`` without bound.
|
||||
"""
|
||||
if not key:
|
||||
return None
|
||||
serve = config.serve or {}
|
||||
dashboard = serve.get("dashboard")
|
||||
known = {str(k) for k in _users()} | {str(serve.get("api_secret") or "")}
|
||||
if isinstance(dashboard, dict) and dashboard.get("key"):
|
||||
known.add(str(dashboard["key"]))
|
||||
return key if key in known else None
|
||||
|
||||
|
||||
def mask_key(key: Optional[str]) -> str:
|
||||
"""A display label for an API key: its configured username, else a truncated prefix."""
|
||||
if not key:
|
||||
return "anonymous"
|
||||
user = (config.serve or {}).get("users", {}).get(key)
|
||||
if isinstance(user, dict) and user.get("username"):
|
||||
user = _user_config(key)
|
||||
if user and user.get("username"):
|
||||
return str(user["username"])
|
||||
return key[:4] + "…"
|
||||
|
||||
|
||||
def key_id(key: Optional[str]) -> str:
|
||||
"""A stable id for an API key. A hash prefix, so two unnamed keys never collide the way
|
||||
``mask_key`` does, and the id carries no key material."""
|
||||
if not key:
|
||||
return "anonymous"
|
||||
return hashlib.sha256(key.encode()).hexdigest()[:12]
|
||||
|
||||
|
||||
def key_tier(key: Optional[str]) -> Optional[str]:
|
||||
"""The tier name a key references, when it names one that exists."""
|
||||
user = _user_config(key)
|
||||
tier = user.get("tier") if user else None
|
||||
return str(tier) if tier else None
|
||||
|
||||
|
||||
def key_rate_limit(key: Optional[str]) -> Optional[int]:
|
||||
"""Requests per hour allowed for a key: its own override, else its tier's, else unlimited."""
|
||||
user = _user_config(key)
|
||||
if user is None:
|
||||
return None
|
||||
own = user.get("rate_limit")
|
||||
if isinstance(own, int) and own > 0:
|
||||
return own
|
||||
tiers = (config.serve or {}).get("tiers")
|
||||
tier = tiers.get(user.get("tier")) if isinstance(tiers, dict) and user.get("tier") else None
|
||||
limit = tier.get("rate_limit") if isinstance(tier, dict) else None
|
||||
return limit if isinstance(limit, int) and limit > 0 else None
|
||||
|
||||
|
||||
def rate_limit_error(where: str, value: Any) -> Optional[str]:
|
||||
"""Why *value* cannot serve as a rate limit, or None when it can. Unset is fine.
|
||||
|
||||
``key_rate_limit`` reads anything else as "no limit", so a mistyped value would silently
|
||||
remove the cap the operator wrote down. It lives beside the reader so the two rules cannot
|
||||
drift apart.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
return f"{where}.rate_limit must be a positive whole number of requests per hour, not {value!r}"
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class KeyStats:
|
||||
"""Per-key counters and the current rate-limit window."""
|
||||
|
||||
label: str
|
||||
requests: int = 0
|
||||
rejected: int = 0
|
||||
bytes_out: int = 0
|
||||
last_seen: float = 0.0
|
||||
window_start: float = 0.0
|
||||
window_used: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerStats:
|
||||
started_at: float = field(default_factory=time.time)
|
||||
@@ -33,7 +118,45 @@ class ServerStats:
|
||||
mode: str = "full"
|
||||
requests_total: int = 0
|
||||
requests_rejected: int = 0
|
||||
requests_by_key: Counter = field(default_factory=Counter)
|
||||
keys: Dict[str, KeyStats] = field(default_factory=dict)
|
||||
|
||||
def key_stats(self, key: Optional[str]) -> KeyStats:
|
||||
"""The counters for an API key, created on first sight."""
|
||||
kid = key_id(key)
|
||||
entry = self.keys.get(kid)
|
||||
if entry is None:
|
||||
entry = KeyStats(label=mask_key(key))
|
||||
self.keys[kid] = entry
|
||||
else:
|
||||
entry.label = mask_key(key)
|
||||
return entry
|
||||
|
||||
@property
|
||||
def requests_by_key(self) -> Counter:
|
||||
"""Legacy label-keyed request counts. Two keys sharing a masked label still merge here;
|
||||
the dashboard reads /api/dashboard/keys for unambiguous per-key figures."""
|
||||
counter: Counter = Counter()
|
||||
for entry in self.keys.values():
|
||||
counter[entry.label] += entry.requests
|
||||
return counter
|
||||
|
||||
def check_rate_limit(self, key: str) -> Optional[int]:
|
||||
"""Seconds to wait when *key* is over its hourly limit, else None after counting the request.
|
||||
|
||||
A fixed window, not a sliding one: cheap, and an operator cap does not need the precision.
|
||||
"""
|
||||
limit = key_rate_limit(key)
|
||||
if limit is None:
|
||||
return None
|
||||
entry = self.key_stats(key)
|
||||
now = time.time()
|
||||
if now - entry.window_start >= RATE_LIMIT_WINDOW:
|
||||
entry.window_start = now
|
||||
entry.window_used = 0
|
||||
if entry.window_used >= limit:
|
||||
return max(1, int(entry.window_start + RATE_LIMIT_WINDOW - now))
|
||||
entry.window_used += 1
|
||||
return None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
@@ -63,7 +186,12 @@ async def stats_middleware(request: web.Request, handler: Any) -> web.StreamResp
|
||||
if response.status == 401:
|
||||
stats.requests_rejected += 1
|
||||
else:
|
||||
stats.requests_by_key[mask_key(request_secret_key(request))] += 1
|
||||
entry = stats.key_stats(configured_key(request_secret_key(request)))
|
||||
entry.requests += 1
|
||||
entry.last_seen = time.time()
|
||||
entry.bytes_out += getattr(response, "content_length", None) or 0
|
||||
if response.status >= 400:
|
||||
entry.rejected += 1
|
||||
session_id = request.match_info.get("session_id")
|
||||
if session_id and request.method != "OPTIONS" and not request.path.endswith("/logs"):
|
||||
from unshackle.core.api.session_store import get_session_store
|
||||
|
||||
@@ -14,8 +14,13 @@ from unshackle.core.utils.redact import mask_proxy
|
||||
log = logging.getLogger("proxies")
|
||||
|
||||
|
||||
def initialize_proxy_providers() -> List[Any]:
|
||||
"""Initialise and return available proxy providers from config."""
|
||||
def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
"""Initialise and return available proxy providers from config.
|
||||
|
||||
A provider that fails to build is logged and skipped, unless *raise_errors* is set.
|
||||
*quiet* drops the per-provider summary lines: rendering a provider asks some of them for
|
||||
their server catalog over the network, which a repeated caller must not pay for.
|
||||
"""
|
||||
proxy_providers: list = []
|
||||
try:
|
||||
from unshackle.core import binaries
|
||||
@@ -45,13 +50,16 @@ def initialize_proxy_providers() -> List[Any]:
|
||||
if hasattr(binaries, "HolaProxy") and binaries.HolaProxy:
|
||||
proxy_providers.append(Hola())
|
||||
|
||||
for provider in proxy_providers:
|
||||
log.info(f"Loaded {provider.__class__.__name__}: {provider}")
|
||||
if not quiet:
|
||||
for provider in proxy_providers:
|
||||
log.info(f"Loaded {provider.__class__.__name__}: {provider}")
|
||||
|
||||
if not proxy_providers:
|
||||
log.warning("No proxy providers were loaded. Check your proxy provider configuration in unshackle.yaml")
|
||||
if not proxy_providers:
|
||||
log.warning("No proxy providers were loaded. Check your proxy provider configuration in unshackle.yaml")
|
||||
|
||||
except Exception as e:
|
||||
if raise_errors:
|
||||
raise
|
||||
log.warning(f"Failed to initialize some proxy providers: {e}")
|
||||
|
||||
return proxy_providers
|
||||
|
||||
@@ -11,6 +11,7 @@ import base64
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import date as date_
|
||||
from enum import Enum
|
||||
@@ -902,6 +903,10 @@ class RemoteService:
|
||||
if cache_data:
|
||||
create_data["cache"] = cache_data
|
||||
|
||||
from unshackle.core import __version__
|
||||
|
||||
create_data["client"] = {"version": __version__, "platform": sys.platform}
|
||||
|
||||
result = self.client.post("/api/session/create", create_data)
|
||||
self._session_id = result["session_id"]
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import logging
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
@@ -13,7 +14,7 @@ import click
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.service_repo import DirtyServiceRepo, is_repo_spec, refresh_repo, resolve_service_repo
|
||||
from unshackle.core.service_repo import DirtyServiceRepo, head, is_repo_spec, refresh_repo, resolve_service_repo
|
||||
from unshackle.core.utilities import import_module_by_path
|
||||
from unshackle.core.utils.redact import redact_path
|
||||
|
||||
@@ -127,9 +128,42 @@ register_service_binaries(MODULES)
|
||||
ALIASES = {tag: getattr(module, "ALIASES", ()) for tag, module in MODULES.items()}
|
||||
|
||||
PENDING: set[str] = set()
|
||||
PENDING_SINCE: dict[str, float] = {}
|
||||
LOADED_COMMITS: dict[str, str] = {}
|
||||
RELOAD_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def record_loaded_commits(tags: Iterable[str] | None = None) -> None:
|
||||
"""Stamp the repo HEAD each tag was imported from, so a staged update is visibly different.
|
||||
|
||||
``refresh_and_reload`` pulls before it defers a reload, so the working tree already holds
|
||||
the new commit while the import is still the old one; without this the two are the same
|
||||
hash and the staged state cannot be told apart.
|
||||
"""
|
||||
wanted = set(tags) if tags is not None else None
|
||||
by_dir: dict[Path, str | None] = {}
|
||||
for path in SERVICES:
|
||||
tag = path.parent.stem
|
||||
if wanted is not None and tag not in wanted:
|
||||
continue
|
||||
source = path.parent.parent
|
||||
if source not in by_dir:
|
||||
by_dir[source] = head(source) if (source / ".git").exists() else None
|
||||
commit = by_dir[source]
|
||||
if commit:
|
||||
LOADED_COMMITS[tag] = commit
|
||||
else:
|
||||
LOADED_COMMITS.pop(tag, None)
|
||||
|
||||
|
||||
def service_source_dir(tag: str) -> Path | None:
|
||||
"""The directory a tag was discovered in: its repo clone, or a local services dir."""
|
||||
for path in SERVICES:
|
||||
if path.parent.stem == tag:
|
||||
return path.parent.parent
|
||||
return None
|
||||
|
||||
|
||||
def reload_services(tags: Iterable[str]) -> list[str]:
|
||||
"""Re-import the given service tags after a repo refresh; returns load errors.
|
||||
|
||||
@@ -151,6 +185,7 @@ def reload_services(tags: Iterable[str]) -> list[str]:
|
||||
SHADOWED[:] = shadowed
|
||||
|
||||
errors: list[str] = []
|
||||
imported: list[str] = []
|
||||
found = {path.parent.stem: path for path in paths}
|
||||
for tag in wanted:
|
||||
if tag not in found:
|
||||
@@ -160,11 +195,17 @@ def reload_services(tags: Iterable[str]) -> list[str]:
|
||||
try:
|
||||
MODULES[tag] = load_service(found[tag])
|
||||
ALIASES[tag] = getattr(MODULES[tag], "ALIASES", ())
|
||||
imported.append(tag)
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
LOAD_ERRORS.extend(errors)
|
||||
register_service_binaries(MODULES)
|
||||
PENDING.difference_update(wanted)
|
||||
for tag in wanted:
|
||||
PENDING_SINCE.pop(tag, None)
|
||||
# Only the tags that imported: a failed re-import keeps the old module running, so
|
||||
# stamping it with the new HEAD would name code that is not running.
|
||||
record_loaded_commits(imported)
|
||||
return errors
|
||||
|
||||
|
||||
@@ -191,6 +232,9 @@ def refresh_and_reload(busy: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
tags.update(p.parent.stem for p in dest.glob("*/__init__.py"))
|
||||
deferred = sorted(tags & busy)
|
||||
PENDING.update(deferred)
|
||||
now = time.time()
|
||||
for tag in deferred:
|
||||
PENDING_SINCE.setdefault(tag, now)
|
||||
errors = reload_services(tags - busy)
|
||||
repos.append(
|
||||
{
|
||||
@@ -204,13 +248,25 @@ def refresh_and_reload(busy: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
return repos
|
||||
|
||||
|
||||
def failed_tags(errors: Iterable[str]) -> set[str]:
|
||||
"""The tags named by a list of load errors, which are all formatted ``TAG: reason``."""
|
||||
return {err.split(":", 1)[0] for err in errors if ":" in err}
|
||||
|
||||
|
||||
def apply_pending(busy: set[str] | None = None) -> list[str]:
|
||||
"""Reload every staged tag whose service is no longer busy; returns the tags applied."""
|
||||
"""Reload every staged tag whose service is no longer busy; returns the tags now running.
|
||||
|
||||
A tag whose re-import failed is not one of them: the old module keeps serving, so calling
|
||||
it applied would tell the dashboard that code is live when it is not.
|
||||
"""
|
||||
ready = sorted(PENDING - (busy or set()))
|
||||
if ready:
|
||||
for err in reload_services(ready):
|
||||
log.error("Service reload failed: %s", err)
|
||||
return ready
|
||||
if not ready:
|
||||
return []
|
||||
errors = reload_services(ready)
|
||||
for err in errors:
|
||||
log.error("Service reload failed: %s", err)
|
||||
failed = failed_tags(errors)
|
||||
return [tag for tag in ready if tag not in failed]
|
||||
|
||||
|
||||
SUMMARY_LOGGED = False
|
||||
|
||||
Reference in New Issue
Block a user