diff --git a/.env.template b/.env.template index 8070b74..010cb85 100644 --- a/.env.template +++ b/.env.template @@ -8,8 +8,15 @@ # --- Docker Compose project name (keeps all containers on the same network) --- COMPOSE_PROJECT_NAME=drsproject +# Host address the internal APIs are published on: InfluxDB 8086, Foresight 8081, backup 8082. The +# dashboard reaches them over the compose network, so the default publishes them for this host only. +# Set 0.0.0.0 only to reach them from elsewhere (a Grafana on another machine reading InfluxDB), and then +# restrict them in a firewall in front of Docker (Docker's published ports bypass ufw). +HCM_INTERNAL_BIND=127.0.0.1 + # --- Clusters --- -# HyperCore clusters are registered in the dashboard (Settings -> Clusters), not here. +# HyperCore clusters are registered in the dashboard (+ Cluster in a folder under Settings -> Access +# -> Tenants), not here. # Their credentials are stored encrypted in PostgreSQL with this key. Generate one with # python3 -c "import secrets; print(secrets.token_hex(32))" # Back it up together with the database: without it the stored passwords are unrecoverable. @@ -54,13 +61,14 @@ SC_SSH_KEY_PATH=/root/.ssh # --- Dashboard --- # Initial admin credentials — used ONLY to seed the first user row on a fresh deployment. -# After that, manage users from the Settings → Users panel inside the dashboard. +# After that, manage accounts under Settings → Access inside the dashboard. # Leave SC_DASHBOARD_USER blank to disable authentication entirely (dev/local mode). SC_DASHBOARD_USER=admin SC_DASHBOARD_PASSWORD=CHANGE_ME # Session signing key — generate with: python -c "import secrets; print(secrets.token_hex(32))" -# If left blank a random key is generated at startup (sessions won't survive restarts). +# If left blank it is derived from HCM_SECRET_KEY. The dashboard refuses to start while it, HCM_SECRET_KEY or +# SC_DASHBOARD_PASSWORD still reads CHANGE_ME. SC_DASHBOARD_SECRET_KEY=CHANGE_ME # A VM console opened from HCM closes after this many minutes without keyboard or mouse input, # and after this many hours in any case. Every console session is in Settings -> Console. @@ -70,6 +78,13 @@ CONSOLE_MAX_HOURS=8 # (publish only /guest/ there, see the manual). Settings -> Mail -> "Address in guest console links" overrides # this. Both blank: links use the address the granter's browser used. HCM_GUEST_BASE_URL= +# Behind a reverse proxy: how many proxies stand in front of HCM (1 for one nginx/Caddy/Traefik). HCM then +# takes the client's address from X-Forwarded-For for the audit log and the sign-in limit; 0 (default) uses +# the connecting address, which is right when browsers connect to port 5000 directly. +HCM_TRUSTED_PROXIES=0 +# true: the session cookie is only ever sent over HTTPS. Leave false when HCM is reached over plain HTTP +# (the cookie is marked Secure anyway on a request that arrived over HTTPS). +HCM_SESSION_COOKIE_SECURE=false # OTP is now configured per-user inside the dashboard Settings → My Account panel. # ============================================================================= @@ -142,7 +157,7 @@ SENTINEL_API_TOKEN=CHANGE_ME # ============================================================================= # --- C7: Right-sizing outcome tracking --- -# Sentinel uses the cluster credentials from the registry (Settings -> Clusters) +# Sentinel uses the cluster credentials from the registry (Settings -> Access -> Tenants) # to detect VM spec changes after a recommendation. # Enable/disable outcome tracking entirely: SENTINEL_OUTCOME_TRACKER_ENABLED=true diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 908a8b4..bb19ea0 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -9,7 +9,7 @@ labels: bug **Environment** - Host OS and architecture (`uname -m`): - Docker / Compose versions (`docker compose version`): -- Profile in use (`core`, `sentinel`, `full`): +- Modules you stopped, if any (`docker compose ps` shows what runs): **What happened** diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 810f1c8..f846f5e 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -17,6 +17,6 @@ how to contact you; a maintainer will follow up privately for the details. ## Hardening Before exposing the stack to any network beyond localhost, work through the Security Hardening -Checklist in [the installing chapter of the manual](docs/manual/08-installing-and-updating.md#securing-the-installation): strong secrets, TLS in front of the dashboard, no host -port bindings for InfluxDB and Sentinel, and an extended dry-run observation period before +Checklist in [the installing chapter of the manual](../docs/manual/08-installing-and-updating.md#securing-the-installation): strong secrets, TLS in front of the dashboard, +the internal APIs (InfluxDB, Foresight, backup) left on 127.0.0.1, and an extended dry-run observation period before enabling live migrations. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2281abd..3c2b85d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,9 +13,52 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.12" + - name: qemu-img and qemu-io for the qcow2 delta tests (skipped without them) + run: sudo apt-get update -qq && sudo apt-get install -y -qq qemu-utils - run: pip install -r tests/requirements.txt - run: pytest -m "not integration" + migrations-twice: + # The dashboard's migration runner applies every postgres/init file again on an install whose database + # was created by initdb (nothing is recorded yet). A file that is not idempotent against the later files + # blocks every later migration and every in-app update of a fresh install (021 did, 1.3.0 to 1.8.0). + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_DB: hypercore_balancer + POSTGRES_USER: sentinel + POSTGRES_PASSWORD: ci + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U sentinel" --health-interval 2s --health-timeout 5s --health-retries 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install psycopg2-binary==2.9.13 + - name: initdb pass (as the postgres image does on a new volume) + env: {PGPASSWORD: ci} + run: | + for f in postgres/init/*.sql; do + psql -v ON_ERROR_STOP=1 -q -h localhost -U sentinel -d hypercore_balancer -f "$f" || exit 1 + done + - name: the dashboard's runner applies every file again, twice + run: | + python - <<'PY' + import sys, psycopg2, psycopg2.extras + sys.path.insert(0, 'dashboard') + import migrations + conn = psycopg2.connect(host='localhost', dbname='hypercore_balancer', user='sentinel', password='ci', + cursor_factory=psycopg2.extras.RealDictCursor) # as the dashboard connects + first = migrations.apply_pending(conn, 'postgres/init') + second = migrations.apply_pending(conn, 'postgres/init') + print(f'applied {len(first)} file(s), then {len(second)}') + assert first and not second + PY + compose-build: runs-on: ubuntu-latest steps: diff --git a/Balancer/Dockerfile b/Balancer/Dockerfile index e95a1ee..8e5a327 100644 --- a/Balancer/Dockerfile +++ b/Balancer/Dockerfile @@ -1,12 +1,15 @@ -FROM python:3.11-slim +# the Debian release is named: package names (apt) differ between releases, and a rebuild must not +# move to the next one unasked +FROM python:3.11-slim-trixie WORKDIR /app # Install build dependencies required by Prophet RUN apt-get update && apt-get install -y build-essential && rm -rf /var/lib/apt/lists/* -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY requirements.txt constraints.txt ./ +# constraints.txt: every transitive package at the version this release was tested with +RUN pip install --no-cache-dir -r requirements.txt -c constraints.txt # Copy your scripts into the container COPY HyperCore_balancer.py . diff --git a/Balancer/HyperCore_balancer.py b/Balancer/HyperCore_balancer.py index 5f28283..b5f13f8 100644 --- a/Balancer/HyperCore_balancer.py +++ b/Balancer/HyperCore_balancer.py @@ -47,6 +47,18 @@ def get_config(key: str, default: Any, cast_type: type = str) -> Any: # clusters (host + credentials) live in the registry, configured in the dashboard; # the balancer runs one LoadBalancer per enabled cluster REGISTRY_POLL_SECONDS = 60 +# a cluster thread that died (crash or refused login) is restarted after 1, 2, 4 … minutes, at most +# every half hour: each restart is a new login, and HyperCore limits logins per hour +RESTART_BACKOFF_MAX_SECONDS = 1800 +HEALTHY_RUN_SECONDS = 900 # a thread that ran this long before dying starts the backoff afresh +# a migration task the cluster no longer reports on must not hold the balancer forever +TASK_DEADLINE_SECONDS = 1800 +TASK_MAX_UNKNOWN = 30 # consecutive UNKNOWN/UNINITIALIZED answers (~5 min at 10 s) +# an affinity move the cluster refused is retried for that VM after 5, 10, 20 … minutes, at most hourly +AFFINITY_RETRY_BASE_SECONDS = 300 +AFFINITY_RETRY_MAX_SECONDS = 3600 +# in dry-run a lasting affinity violation is reported once a day, not every sample interval +AFFINITY_DRY_REPORT_SECONDS = 86400 # influxdb target for migration events — configurables INFLUX_URL = get_config('INFLUX_URL', "http://influxdb:8086") @@ -199,7 +211,7 @@ def __init__(self, client: HyperCoreApiClient, config: Dict, migration_logger: M self.cluster_id = cluster.cluster_id if cluster is not None else TEMPLATE_CLUSTER_ID self.cluster_name = cluster.name if cluster is not None else 'cluster' self.stop = stop_event or threading.Event() - self.max_history = int((config['AVG_WINDOW_MINUTES'] * 60) / config['SAMPLE_INTERVAL_SECONDS']) + self.max_history = self._window_samples() self.node_cpu_history = {} self.node_ram_history = {} @@ -208,6 +220,8 @@ def __init__(self, client: HyperCoreApiClient, config: Dict, migration_logger: M self.vm_cooldowns = {} self.last_migration_time = 0 self.active_task = None + self._affinity_backoff = {} # vm_uuid -> (refusals in a row, earliest next attempt) + self._affinity_reported = {} # dry-run: vm_uuid -> when its violation was last reported self.last_predictive_run = 0 self.reserved_nodes = {} @@ -227,7 +241,7 @@ def reload_config(self): self.log(1, f"[CONFIG] {key}: {self.config[key]} → {new[key]}") self.config[key] = new[key] # recalculate derived window size; clear histories if it changed - new_max = int((self.config['AVG_WINDOW_MINUTES'] * 60) / self.config['SAMPLE_INTERVAL_SECONDS']) + new_max = self._window_samples() if new_max != self.max_history: self.max_history = new_max self.node_cpu_history.clear() @@ -235,6 +249,12 @@ def reload_config(self): self.vm_cpu_history.clear() self.log(0, f"[CONFIG] History window resized to {self.max_history} samples — buffers cleared.") + def _window_samples(self) -> int: + """Samples in the averaging window; at least one. A window shorter than one sample interval + (1 min at 120 s, both allowed by the settings) gave 0: a deque of length 0, whose mean() + raised and killed the cluster's thread, and the supervisor logged in again every minute.""" + return max(1, int((self.config['AVG_WINDOW_MINUTES'] * 60) / self.config['SAMPLE_INTERVAL_SECONDS'])) + def log(self, level: int, message: str): if level == 0 or self.config['VERBOSITY'] >= level: ts = time.strftime("%Y-%m-%d %H:%M:%S") @@ -280,7 +300,7 @@ def evaluate_cluster(self, nodes, vms) -> Dict: "tags": vm.get('tags', "") }) - threads = n.get('numThreads', 1) + threads = n.get('numThreads') or 1 # 0 or missing would divide by zero below allocated_vcpus = sum(vm['vcpus'] for vm in vms_on_node) is_usable = n.get('networkStatus') == 'ONLINE' and n.get('allowRunningVMs', True) @@ -331,37 +351,16 @@ def select_candidate(self, state: Dict) -> Tuple: self.log(3, f" - Skipping {vm['name']} (cooldown active)") continue - # anti-affinity sets for the candidate VM - vm_anti = {t.strip()[5:] for t in vm['tags'].split(',') if t.strip().startswith('anti_')} - tol = self.config.get('CPU_TARGET_TOLERANCE_PERCENT', 5.0) targets = sorted(usable, key=lambda x: x['avg_ram'] if mode == "RAM_FOCUS" else (int(x['avg_cpu'] / tol), x['avg_ram'])) for tgt in targets: - if tgt['name'] == src['name']: continue - - if tgt['uuid'] in self.reserved_nodes: - if time.time() < self.reserved_nodes[tgt['uuid']]: - self.log(3, f" - Skipping target node {tgt['name']} (Reserved for impending predicted spike)") - continue - else: - del self.reserved_nodes[tgt['uuid']] - - # anti-affinity: skip if candidate's anti_X tag matches a VM name on target, - # or if any VM on target has anti_ pointing back at us - tgt_names = {v['name'] for v in tgt['vms']} - tgt_anti = {t.strip()[5:] for v in tgt['vms'] for t in v['tags'].split(',') if t.strip().startswith('anti_')} - if vm_anti & tgt_names: - self.log(2, f" - Skipping target {tgt['name']}: anti-affinity ({vm_anti & tgt_names})") - continue - if vm['name'] in tgt_anti: - self.log(2, f" - Skipping target {tgt['name']}: anti-affinity (reverse block on {vm['name']})") + refusal = self.target_refusal(vm, src, tgt) + if refusal: + level, why = refusal + self.log(level, f" - Skipping target {tgt['name']}: {why}") continue p_ram = ((tgt['used_ram'] + vm['mem']) / tgt['total_ram']) * 100 - p_ratio = (sum(v['vcpus'] for v in tgt['vms']) + vm['vcpus']) / tgt['threads'] - - if p_ram > self.config['RAM_LIMIT_PERCENT'] or p_ratio > self.config['MAX_VCPU_RATIO']: - continue # reject targets whose post-move RAM would exceed the upper threshold — # landing there makes them a RAM_FOCUS source candidate next cycle if mode == "RAM_FOCUS" and p_ram > self.config['RAM_UPPER_THRESHOLD_PERCENT']: @@ -374,10 +373,60 @@ def select_candidate(self, state: Dict) -> Tuple: return vm, src, tgt, mode return None, None, None, primary - def find_affinity_violation(self, usable): + def target_refusal(self, vm, src, tgt): + """Why `tgt` cannot take `vm` (running on `src`) now, as (log level, reason), or None. The + target test every engine's move must pass: a usable node (online, allows running VMs, so + no witness or maintenance node, not excluded) other than the source, not reserved for a + predicted spike, not against the VM's node pin or anyone's anti-affinity, and within the + RAM limit and the vCPU ratio after the move.""" + if tgt['uuid'] == src['uuid']: + return 3, "is the source" + if not tgt['is_usable']: + return 2, "not usable (offline, excluded, maintenance or witness)" + if tgt['uuid'] in self.reserved_nodes: + if time.time() < self.reserved_nodes[tgt['uuid']]: + return 3, "reserved for impending predicted spike" + del self.reserved_nodes[tgt['uuid']] + tags = [t.strip() for t in vm['tags'].split(',')] + pin = next((t[5:] for t in tags if t.startswith('node_')), None) + if pin and pin != tgt['name'].split('.')[-1]: + return 2, f"{vm['name']} is pinned to node_{pin}" + # anti-affinity: skip if candidate's anti_X tag matches a VM name on target, + # or if any VM on target has anti_ pointing back at us + vm_anti = {t[5:] for t in tags if t.startswith('anti_')} + tgt_names = {v['name'] for v in tgt['vms']} + tgt_anti = {t.strip()[5:] for v in tgt['vms'] for t in v['tags'].split(',') if t.strip().startswith('anti_')} + if vm_anti & tgt_names: + return 2, f"anti-affinity ({vm_anti & tgt_names})" + if vm['name'] in tgt_anti: + return 2, f"anti-affinity (reverse block on {vm['name']})" + p_ram = ((tgt['used_ram'] + vm['mem']) / tgt['total_ram']) * 100 + p_ratio = (sum(v['vcpus'] for v in tgt['vms']) + vm['vcpus']) / tgt['threads'] + if p_ram > self.config['RAM_LIMIT_PERCENT']: + return 3, f"RAM would reach {p_ram:.0f}%" + if p_ratio > self.config['MAX_VCPU_RATIO']: + return 3, f"vCPU ratio would reach {p_ratio:.2f}" + return None + + def _predictive_refusal(self, rec, state): + """Why a queued Oracle recommendation must not run now, or None. It may be up to a day + old, so the VM, the source and the target are checked against the current state.""" + src = state.get(rec.source_node) + vm = next((v for v in src['vms'] if v['uuid'] == rec.vm_uuid), None) if src else None + if vm is None: + return f"VM '{rec.vm_name}' is no longer running on {rec.source_ip}" + tgt = state.get(rec.target_node) + if tgt is None: + return f"target node {rec.target_ip} is no longer in the cluster" + refusal = self.target_refusal(vm, src, tgt) + return f"target {rec.target_ip} {refusal[1]}" if refusal else None + + def find_affinity_violation(self, usable, skip=frozenset()): """ Highest-priority pass: detect and return one remediation move for any affinity violation. - Bypasses migration cooldown and per-VM cooldown — affinity is always fixed first. + Bypasses migration cooldown and per-VM cooldown — affinity is always fixed first. VMs in + `skip` (a refused move waiting for its retry, or a dry-run violation already reported) + are not moved, so the next violation gets its turn. Checks (in priority order): 1. Anti-affinity: VM with anti_X tag sharing a node with VM named X @@ -414,6 +463,8 @@ def _find_room_move(target_node): for blocker in sorted(target_node['vms'], key=lambda v: v['mem']): if _pinned_suffix(blocker) == target_node['name'].split('.')[-1]: continue # cannot evict a VM pinned to this node + if blocker['uuid'] in skip: + continue blocker_anti = {t.strip()[5:] for t in blocker['tags'].split(',') if t.strip().startswith('anti_')} for dest in sorted(usable, key=lambda n: n['avg_cpu']): @@ -433,7 +484,7 @@ def _find_room_move(target_node): vm_anti = {t.strip()[5:] for t in vm['tags'].split(',') if t.strip().startswith('anti_')} conflicts = vm_anti & names_here - if not conflicts: + if not conflicts or vm['uuid'] in skip: continue self.log(1, f"[AFFINITY] VIOLATION: {vm['name']} shares {src['name']} " @@ -463,8 +514,8 @@ def _find_room_move(target_node): src_suffix = src['name'].split('.')[-1] for vm in src['vms']: pin = _pinned_suffix(vm) - if not pin or pin == src_suffix: - continue # not pinned, or already on correct node + if not pin or pin == src_suffix or vm['uuid'] in skip: + continue # not pinned, already on correct node, or waiting tgt = next((n for n in usable if n['name'].split('.')[-1] == pin), None) if not tgt: @@ -517,234 +568,280 @@ def start(self): try: while not self.stop.is_set(): - # hot-reload tunables every 60 seconds - now_ts = time.time() - if now_ts - self._last_config_check > 60: - self.reload_config() - self._last_config_check = now_ts - - if self.active_task: - status = self.client.get_task_status(self.active_task['tag']) - if status in ["COMPLETE", "ERROR"]: - self.log(0, f"Migration {status} for {self.active_task['vm']}") - self.active_task = None - self.last_migration_time = time.time() - self._sleep(10); continue + try: + delay = self._cycle() + except Exception as e: # noqa: BLE001 one bad cycle must not end the thread (and cost a login) + self.log(0, f"[ERROR] Balancing cycle failed: {e}") + traceback.print_exc() + delay = self.config.get('SAMPLE_INTERVAL_SECONDS') or 30 + self._sleep(delay) + except KeyboardInterrupt: self.log(0, "Shutdown requested.") + finally: + self.log(0, "Balancer stopped for this cluster.") + self.client.close() + self.migration_logger.close() + + def _cycle(self) -> float: + """One pass of the balancing loop; returns the seconds to wait before the next.""" + # hot-reload tunables every 60 seconds + now_ts = time.time() + if now_ts - self._last_config_check > 60: + self.reload_config() + self._last_config_check = now_ts + + if self.active_task: + task = self.active_task + status = self.client.get_task_status(task['tag']) + if status in ["COMPLETE", "ERROR"]: + self.log(0, f"Migration {status} for {task['vm']}") + self.active_task = None + self.last_migration_time = time.time() + return 10 + # UNKNOWN: the status could not be read; UNINITIALIZED: the cluster does not know the tag + task['unknown'] = task.get('unknown', 0) + 1 if status in ("UNKNOWN", "UNINITIALIZED") else 0 + age = time.time() - task.setdefault('started', time.time()) + if age > TASK_DEADLINE_SECONDS or task['unknown'] >= TASK_MAX_UNKNOWN: + why = (f"no status for {task['unknown']} checks" if task['unknown'] >= TASK_MAX_UNKNOWN + else f"still {status} after {int(age // 60)} min") + self.log(0, f"[TASK] Giving up on migration task {task['tag']} for {task['vm']} ({why}); " + f"re-reading placement.") + self.active_task = None + self.last_migration_time = time.time() + return 10 + try: + nodes, vms, stats = self.client.get_nodes(), self.client.get_vms(), self.client.get_vm_stats() + self.update_metrics(nodes, stats) + except Exception as e: + self.log(0, f"API Fetch Error: {e}"); return 30 + + # evaluate cluster state once — shared by affinity, predictive, and reactive engines + state = self.evaluate_cluster(nodes, vms) + usable = [n for n in state.values() if n['is_usable']] + + # ================================================================= + # affinity enforcement — highest priority, bypasses all cooldowns + # ================================================================= + now = time.time() + dry_run = self.config['DRY_RUN'] + if dry_run: + self._affinity_reported = {u: t for u, t in self._affinity_reported.items() + if now - t < AFFINITY_DRY_REPORT_SECONDS} + skip = set(self._affinity_reported) + else: + skip = {u for u, (_, until) in self._affinity_backoff.items() if until > now} + aff_vm, aff_src, aff_tgt, aff_reason = self.find_affinity_violation(usable, skip) + if aff_vm: + info = f"{aff_vm['name']} | {aff_src['name']} -> {aff_tgt['name']} (Affinity: {aff_reason})" + aff_mode = "anti-affinity" if "anti-affinity" in aff_reason.lower() else "node-affinity" + if dry_run: + # reported once (again after a day); nothing moves, so the reactive and predictive + # engines below still get their turn instead of being skipped every cycle + self.log(0, f"[AFFINITY DRY RUN] Would move {info}") + self._affinity_reported[aff_vm['uuid']] = now + self.vm_cooldowns[aff_vm['uuid']] = now + else: + self.log(0, f"[AFFINITY ACTION] {info}") try: - nodes, vms, stats = self.client.get_nodes(), self.client.get_vms(), self.client.get_vm_stats() - self.update_metrics(nodes, stats) + task = self.client.migrate(aff_vm['uuid'], aff_tgt['uuid']) + self.active_task = {"tag": task['taskTag'], "vm": aff_vm['name'], "started": time.time()} + self.vm_cooldowns[aff_vm['uuid']] = time.time() + self.last_migration_time = time.time() + self._affinity_backoff.pop(aff_vm['uuid'], None) except Exception as e: - self.log(0, f"API Fetch Error: {e}"); self._sleep(30); continue - - # evaluate cluster state once — shared by affinity, predictive, and reactive engines - state = self.evaluate_cluster(nodes, vms) - usable = [n for n in state.values() if n['is_usable']] - - # ================================================================= - # affinity enforcement — highest priority, bypasses all cooldowns - # ================================================================= - aff_vm, aff_src, aff_tgt, aff_reason = self.find_affinity_violation(usable) - if aff_vm: - info = f"{aff_vm['name']} | {aff_src['name']} -> {aff_tgt['name']} (Affinity: {aff_reason})" - if self.config['DRY_RUN']: - self.log(0, f"[AFFINITY DRY RUN] Would move {info}") - self.vm_cooldowns[aff_vm['uuid']] = time.time() - self.last_migration_time = time.time() - else: - self.log(0, f"[AFFINITY ACTION] {info}") - try: - task = self.client.migrate(aff_vm['uuid'], aff_tgt['uuid']) - self.active_task = {"tag": task['taskTag'], "vm": aff_vm['name']} - self.vm_cooldowns[aff_vm['uuid']] = time.time() - self.last_migration_time = time.time() - except Exception as e: - self.log(0, f"[AFFINITY ERROR] Migration rejected for {aff_vm['name']}: {e}") - self.vm_cooldowns[aff_vm['uuid']] = time.time() - aff_mode = "anti-affinity" if "anti-affinity" in aff_reason.lower() else "node-affinity" - self.migration_logger.log_event( - vm_name=aff_vm['name'], vm_uuid=aff_vm['uuid'], - source_ip=aff_src['name'], target_ip=aff_tgt['name'], - engine="Affinity", mode=aff_mode, - dry_run=self.config['DRY_RUN'], reason="affinity-violation", - cluster_id=self.cluster_id - ) - self._sleep(self.config['SAMPLE_INTERVAL_SECONDS']) - continue - - # non-affinity migration cooldown - elapsed = time.time() - self.last_migration_time - cluster_cd = self.config['MIGRATION_COOLDOWN_MINUTES'] * 60 - if elapsed < cluster_cd: - self._sleep(self.config['SAMPLE_INTERVAL_SECONDS']); continue - - # ================================================================= - # optional: predictive balancing - # ================================================================= - if self.config['PREDICTIVE_BALANCING_ENABLED']: - applied_predictive = False - now = time.time() - lead_time_seconds = self.config['PREDICTIVE_LEAD_TIME_HOURS'] * 3600 - - # --- store results from a completed forecast thread --- - if self._predictive_thread is not None and not self._predictive_thread.is_alive(): - recommendations = self._predictive_results or [] - self._predictive_results = None - self._predictive_thread = None - self._predictive_overrun_logged = False - - if recommendations: - current_vms = {vm['uuid']: vm for vm in vms} - current_node_uuids = {n['uuid'] for n in nodes} - valid_recs = [] - for rec in recommendations: - vm_current = current_vms.get(rec.vm_uuid) - if not vm_current: - self.log(0, f"[PREDICTIVE] Skipping stale recommendation: VM '{rec.vm_name}' no longer exists in cluster.") - continue - if vm_current.get('nodeUUID') != rec.source_node: - self.log(0, f"[PREDICTIVE] Skipping stale recommendation: VM '{rec.vm_name}' has already moved to a different node.") - continue - if rec.target_node not in current_node_uuids: - self.log(0, f"[PREDICTIVE] Skipping stale recommendation: target node for '{rec.vm_name}' is no longer available.") - continue - valid_recs.append(rec) - - self._pending_predictive_recs = valid_recs - if valid_recs: - earliest = min(valid_recs, key=lambda r: r.peak_time) - earliest_str = time.strftime('%Y-%m-%d %H:%M', time.localtime(earliest.peak_time)) - self.log(0, f"[PREDICTIVE] {len(valid_recs)} recommendation(s) queued. Earliest peak at {earliest_str}.") - - # reserve all source nodes immediately — don't wait for each migration - # to execute. this prevents the reactive engine from routing VMs back - # onto a node the Oracle just decided is going to be overloaded - reservation_secs = self.config.get('PREDICTIVE_RESERVATION_MINUTES', 5) * 60 - seen_sources = set() - for rec in valid_recs: - if rec.source_node in seen_sources: - continue - seen_sources.add(rec.source_node) - release_time = rec.peak_time + reservation_secs - existing = self.reserved_nodes.get(rec.source_node, 0) - if release_time > existing: - self.reserved_nodes[rec.source_node] = release_time - fmt = time.strftime('%Y-%m-%d %H:%M', time.localtime(release_time)) - self.log(0, f"[RESERVATION] Node {rec.source_ip} locked as target until {fmt} (Oracle: predicted overload)") - - # --- discard recommendations whose peak has already passed --- - self._pending_predictive_recs = [r for r in self._pending_predictive_recs if r.peak_time > now] - - # --- act on any recommendation whose peak is within the lead time window --- - ready_recs = [r for r in self._pending_predictive_recs if r.peak_time - now <= lead_time_seconds] - if ready_recs: - rec = ready_recs[0] - self._pending_predictive_recs.remove(rec) - info = f"{rec.vm_name} | {rec.source_ip} -> {rec.target_ip} (Predictive: {rec.reason})" - - if self.config['DRY_RUN']: - self.log(0, f"[PREDICTIVE DRY RUN] Would move {info}") - self.vm_cooldowns[rec.vm_uuid] = time.time() - self.last_migration_time = time.time() - else: - self.log(0, f"[PREDICTIVE ACTION] Migrating {info}") - try: - task = self.client.migrate(rec.vm_uuid, rec.target_node) - self.active_task = {"tag": task['taskTag'], "vm": rec.vm_name} - self.vm_cooldowns[rec.vm_uuid] = time.time() - self.last_migration_time = time.time() - except Exception as e: - self.log(0, f"[PREDICTIVE ERROR] Migration request rejected for {rec.vm_name}: {e}") - self.vm_cooldowns[rec.vm_uuid] = time.time() - applied_predictive = False - continue - - self.migration_logger.log_event( - vm_name=rec.vm_name, vm_uuid=rec.vm_uuid, - source_ip=rec.source_ip, target_ip=rec.target_ip, - engine="predictive", mode="PREDICTIVE", - dry_run=self.config['DRY_RUN'], reason=rec.reason, - cluster_id=self.cluster_id - ) - - reservation_secs = self.config.get('PREDICTIVE_RESERVATION_MINUTES', 5) * 60 + n = self._affinity_backoff.get(aff_vm['uuid'], (0, 0))[0] + 1 + wait = min(AFFINITY_RETRY_MAX_SECONDS, AFFINITY_RETRY_BASE_SECONDS * 2 ** (n - 1)) + self._affinity_backoff[aff_vm['uuid']] = (n, time.time() + wait) + self.vm_cooldowns[aff_vm['uuid']] = time.time() + self.log(0, f"[AFFINITY ERROR] Migration rejected for {aff_vm['name']}: {e} " + f"(next attempt in {wait // 60} min)") + return self.config['SAMPLE_INTERVAL_SECONDS'] # a refused move is not logged as done + self.migration_logger.log_event( + vm_name=aff_vm['name'], vm_uuid=aff_vm['uuid'], + source_ip=aff_src['name'], target_ip=aff_tgt['name'], + engine="Affinity", mode=aff_mode, + dry_run=dry_run, reason="affinity-violation", + cluster_id=self.cluster_id + ) + if not dry_run: + return self.config['SAMPLE_INTERVAL_SECONDS'] + + # non-affinity migration cooldown + elapsed = time.time() - self.last_migration_time + cluster_cd = self.config['MIGRATION_COOLDOWN_MINUTES'] * 60 + if elapsed < cluster_cd: + return self.config['SAMPLE_INTERVAL_SECONDS'] + + # ================================================================= + # optional: predictive balancing + # ================================================================= + if self.config['PREDICTIVE_BALANCING_ENABLED']: + applied_predictive = False + now = time.time() + lead_time_seconds = self.config['PREDICTIVE_LEAD_TIME_HOURS'] * 3600 + + # --- store results from a completed forecast thread --- + if self._predictive_thread is not None and not self._predictive_thread.is_alive(): + recommendations = self._predictive_results or [] + self._predictive_results = None + self._predictive_thread = None + self._predictive_overrun_logged = False + + valid_recs = [] + if recommendations: + current_vms = {vm['uuid']: vm for vm in vms} + current_node_uuids = {n['uuid'] for n in nodes} + for rec in recommendations: + vm_current = current_vms.get(rec.vm_uuid) + if not vm_current: + self.log(0, f"[PREDICTIVE] Skipping stale recommendation: VM '{rec.vm_name}' no longer exists in cluster.") + continue + if vm_current.get('nodeUUID') != rec.source_node: + self.log(0, f"[PREDICTIVE] Skipping stale recommendation: VM '{rec.vm_name}' has already moved to a different node.") + continue + if rec.target_node not in current_node_uuids: + self.log(0, f"[PREDICTIVE] Skipping stale recommendation: target node for '{rec.vm_name}' is no longer available.") + continue + valid_recs.append(rec) + + # a clean forecast clears the queue: recommendations of an earlier run do not survive it + self._pending_predictive_recs = valid_recs + if valid_recs: + earliest = min(valid_recs, key=lambda r: r.peak_time) + earliest_str = time.strftime('%Y-%m-%d %H:%M', time.localtime(earliest.peak_time)) + self.log(0, f"[PREDICTIVE] {len(valid_recs)} recommendation(s) queued. Earliest peak at {earliest_str}.") + + # reserve all source nodes immediately — don't wait for each migration + # to execute. this prevents the reactive engine from routing VMs back + # onto a node the Oracle just decided is going to be overloaded + reservation_secs = self.config.get('PREDICTIVE_RESERVATION_MINUTES', 5) * 60 + seen_sources = set() + for rec in valid_recs: + if rec.source_node in seen_sources: + continue + seen_sources.add(rec.source_node) release_time = rec.peak_time + reservation_secs existing = self.reserved_nodes.get(rec.source_node, 0) if release_time > existing: self.reserved_nodes[rec.source_node] = release_time - formatted_time = time.strftime('%Y-%m-%d %H:%M', time.localtime(release_time)) - self.log(0, f"[RESERVATION] Node {rec.source_ip} locked from receiving VMs until {formatted_time}") - applied_predictive = True - - # --- start a new forecast thread if interval has elapsed --- - jitter = random.uniform(0, self.config['PREDICTIVE_INTERVAL_SECONDS'] * 0.1) - if time.time() - self.last_predictive_run > (self.config['PREDICTIVE_INTERVAL_SECONDS'] + jitter): - if self._predictive_thread is not None and self._predictive_thread.is_alive(): - if not self._predictive_overrun_logged: - self.log(0, "[PREDICTIVE] WARNING: Previous forecast is still running — skipping this interval.") - self._predictive_overrun_logged = True - else: - self.log(0, "[PREDICTIVE] Starting background forecast thread.") - vms_snapshot = list(vms) - nodes_snapshot = list(nodes) - self._predictive_thread = threading.Thread( - target=self._run_predictive_background, - args=(vms_snapshot, nodes_snapshot), - daemon=True, - name="PredictiveEngine" - ) - self._predictive_thread.start() - self.last_predictive_run = time.time() - - if self.active_task or (self.config['DRY_RUN'] and applied_predictive): - self._sleep(self.config['SAMPLE_INTERVAL_SECONDS']) - continue - - # ================================================================= - # reactive balancing - # ================================================================= - first_uid = nodes[0]['uuid'] if nodes else None - if first_uid and len(self.node_cpu_history.get(first_uid, [])) < self.max_history: - self.log(2, f"Buffer: {len(self.node_cpu_history[first_uid])}/{self.max_history}") - self._sleep(self.config['SAMPLE_INTERVAL_SECONDS']); continue - - vm, src, tgt, mode = self.select_candidate(state) - - if vm: - info = f"{vm['name']} | {src['name']} -> {tgt['name']} ({mode})" - if self.config['DRY_RUN']: - self.log(0, f"[REACTIVE DRY RUN] Would move {info}") + fmt = time.strftime('%Y-%m-%d %H:%M', time.localtime(release_time)) + self.log(0, f"[RESERVATION] Node {rec.source_ip} locked as target until {fmt} (Oracle: predicted overload)") + + # --- discard recommendations whose peak has already passed --- + self._pending_predictive_recs = [r for r in self._pending_predictive_recs if r.peak_time > now] + + # --- act on any recommendation whose peak is within the lead time window --- + ready_recs = [r for r in self._pending_predictive_recs if r.peak_time - now <= lead_time_seconds] + rec = None + for candidate in ready_recs: + # the reactive engine's target test, against the state of now: the recommendation + # may be a day old, and its target may since be in maintenance, excluded or full + self._pending_predictive_recs.remove(candidate) + refusal = self._predictive_refusal(candidate, state) + if refusal: + self.log(0, f"[PREDICTIVE] Dropping recommendation {candidate.vm_name} -> {candidate.target_ip}: {refusal}.") + continue + rec = candidate + break + if rec: + info = f"{rec.vm_name} | {rec.source_ip} -> {rec.target_ip} (Predictive: {rec.reason})" + + if self.config['DRY_RUN']: + self.log(0, f"[PREDICTIVE DRY RUN] Would move {info}") + self.vm_cooldowns[rec.vm_uuid] = time.time() + self.last_migration_time = time.time() + else: + self.log(0, f"[PREDICTIVE ACTION] Migrating {info}") + try: + task = self.client.migrate(rec.vm_uuid, rec.target_node) + self.active_task = {"tag": task['taskTag'], "vm": rec.vm_name, "started": time.time()} + self.vm_cooldowns[rec.vm_uuid] = time.time() self.last_migration_time = time.time() - self.vm_cooldowns[vm['uuid']] = time.time() - self.node_cpu_history.clear() - else: - self.log(0, f"[REACTIVE ACTION] Migrating {info}") - try: - task = self.client.migrate(vm['uuid'], tgt['uuid']) - self.active_task = {"tag": task['taskTag'], "vm": vm['name']} - self.vm_cooldowns[vm['uuid']] = time.time() - except Exception as e: - self.log(0, f"[REACTIVE ERROR] Migration request rejected for {vm['name']}: {e}") - self.vm_cooldowns[vm['uuid']] = time.time() - self._sleep(self.config['SAMPLE_INTERVAL_SECONDS']) - continue - - # log the event to InfluxDB for the dashboard - self.migration_logger.log_event( - vm_name=vm['name'], vm_uuid=vm['uuid'], - source_ip=src['name'], target_ip=tgt['name'], - engine="reactive", mode=mode, - dry_run=self.config['DRY_RUN'], - reason=f"Reactive {mode} balancing", - cluster_id=self.cluster_id + except Exception as e: + self.log(0, f"[PREDICTIVE ERROR] Migration request rejected for {rec.vm_name}: {e}") + self.vm_cooldowns[rec.vm_uuid] = time.time() + return 0 + + self.migration_logger.log_event( + vm_name=rec.vm_name, vm_uuid=rec.vm_uuid, + source_ip=rec.source_ip, target_ip=rec.target_ip, + engine="predictive", mode="PREDICTIVE", + dry_run=self.config['DRY_RUN'], reason=rec.reason, + cluster_id=self.cluster_id + ) + + reservation_secs = self.config.get('PREDICTIVE_RESERVATION_MINUTES', 5) * 60 + release_time = rec.peak_time + reservation_secs + existing = self.reserved_nodes.get(rec.source_node, 0) + if release_time > existing: + self.reserved_nodes[rec.source_node] = release_time + formatted_time = time.strftime('%Y-%m-%d %H:%M', time.localtime(release_time)) + self.log(0, f"[RESERVATION] Node {rec.source_ip} locked from receiving VMs until {formatted_time}") + applied_predictive = True + + # --- start a new forecast thread if interval has elapsed --- + jitter = random.uniform(0, self.config['PREDICTIVE_INTERVAL_SECONDS'] * 0.1) + if time.time() - self.last_predictive_run > (self.config['PREDICTIVE_INTERVAL_SECONDS'] + jitter): + if self._predictive_thread is not None and self._predictive_thread.is_alive(): + if not self._predictive_overrun_logged: + self.log(0, "[PREDICTIVE] WARNING: Previous forecast is still running — skipping this interval.") + self._predictive_overrun_logged = True + else: + self.log(0, "[PREDICTIVE] Starting background forecast thread.") + vms_snapshot = list(vms) + # only nodes a VM may run on: the Oracle picks its targets from these + nodes_snapshot = [n for n in nodes if state.get(n['uuid'], {}).get('is_usable')] + self._predictive_thread = threading.Thread( + target=self._run_predictive_background, + args=(vms_snapshot, nodes_snapshot), + daemon=True, + name="PredictiveEngine" ) - - self._sleep(self.config['SAMPLE_INTERVAL_SECONDS']) - except KeyboardInterrupt: self.log(0, "Shutdown requested.") - finally: - self.log(0, "Balancer stopped for this cluster.") - self.client.close() - self.migration_logger.close() + self._predictive_thread.start() + self.last_predictive_run = time.time() + + if self.active_task or (self.config['DRY_RUN'] and applied_predictive): + return self.config['SAMPLE_INTERVAL_SECONDS'] + + # ================================================================= + # reactive balancing + # ================================================================= + first_uid = nodes[0]['uuid'] if nodes else None + if first_uid and len(self.node_cpu_history.get(first_uid, [])) < self.max_history: + self.log(2, f"Buffer: {len(self.node_cpu_history[first_uid])}/{self.max_history}") + return self.config['SAMPLE_INTERVAL_SECONDS'] + + vm, src, tgt, mode = self.select_candidate(state) + + if vm: + info = f"{vm['name']} | {src['name']} -> {tgt['name']} ({mode})" + if self.config['DRY_RUN']: + self.log(0, f"[REACTIVE DRY RUN] Would move {info}") + self.last_migration_time = time.time() + self.vm_cooldowns[vm['uuid']] = time.time() + self.node_cpu_history.clear() + else: + self.log(0, f"[REACTIVE ACTION] Migrating {info}") + try: + task = self.client.migrate(vm['uuid'], tgt['uuid']) + self.active_task = {"tag": task['taskTag'], "vm": vm['name'], "started": time.time()} + self.vm_cooldowns[vm['uuid']] = time.time() + except Exception as e: + self.log(0, f"[REACTIVE ERROR] Migration request rejected for {vm['name']}: {e}") + self.vm_cooldowns[vm['uuid']] = time.time() + return self.config['SAMPLE_INTERVAL_SECONDS'] + + # log the event to InfluxDB for the dashboard + self.migration_logger.log_event( + vm_name=vm['name'], vm_uuid=vm['uuid'], + source_ip=src['name'], target_ip=tgt['name'], + engine="reactive", mode=mode, + dry_run=self.config['DRY_RUN'], + reason=f"Reactive {mode} balancing", + cluster_id=self.cluster_id + ) + + return self.config['SAMPLE_INTERVAL_SECONDS'] class ClusterBalancerThread(threading.Thread): """Runs one LoadBalancer for one registry cluster until its stop event is set.""" @@ -754,6 +851,7 @@ def __init__(self, cluster, migration_logger: MigrationLogger, stop_event: threa self.cluster = cluster self.stop_event = stop_event self.migration_logger = migration_logger + self.started_at = time.time() def run(self): username, password = cluster_registry.credentials(self.cluster.cluster_id) @@ -765,13 +863,44 @@ def run(self): client.interlock = lambda vm_uuid, _cid=self.cluster.cluster_id, _c=client: _busy_reason(_cid, _c, vm_uuid) if not client.login(): cluster_registry.mark_error(self.cluster.cluster_id, 'balancer login failed') - print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [{self.cluster.name}] Login failed — retrying on next registry sync.") + print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [{self.cluster.name}] Login failed — retrying after a backoff.") return config_db.copy_template_to(self.cluster.cluster_id) # pick up tunables added since registration config = config_db.get_all(self.cluster.cluster_id) LoadBalancer(client, config, self.migration_logger, cluster=self.cluster, stop_event=self.stop_event).start() +def reconcile(threads: Dict, clusters: Dict, suspended: set, backoff: Dict, start_thread, now: float) -> None: + """Bring the running cluster threads in line with the registry. A thread is stopped when its + cluster is removed, disabled, suspended or changed (credentials, host), and restarted at once in + the last case. A thread that died on its own (a crash, or a login the cluster refused) is + restarted only after a backoff that doubles per death; before, it was recreated on every + registry pass, which is one new login a minute against the cluster's hourly limit. + `backoff` maps cluster_id -> (deaths in a row, earliest restart, the cluster's updated_at).""" + for cid, (t, ev) in list(threads.items()): + c = clusters.get(cid) + changed = c is None or c.updated_at != t.cluster.updated_at + died = not t.is_alive() + if changed or died or cid in suspended: + ev.set() + del threads[cid] + if died and not changed and cid not in suspended: + n = 0 if now - getattr(t, 'started_at', now) >= HEALTHY_RUN_SECONDS else backoff.get(cid, (0, 0, None))[0] + n += 1 + wait = min(RESTART_BACKOFF_MAX_SECONDS, REGISTRY_POLL_SECONDS * 2 ** (n - 1)) + backoff[cid] = (n, now + wait, c.updated_at) + print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [{c.name}] Balancer thread stopped " + f"({n}x in a row); next attempt in {wait // 60} min.") + for cid, c in clusters.items(): + if cid in suspended or cid in threads: + continue + n, until, seen = backoff.get(cid, (0, 0, None)) + if now < until and seen == c.updated_at: # a changed cluster (new password) is tried at once + continue + ev = threading.Event() + threads[cid] = (start_thread(c, ev), ev) + + def _handle_sigterm(*_): raise KeyboardInterrupt() @@ -784,7 +913,13 @@ def _handle_sigterm(*_): migration_logger = MigrationLogger(INFLUX_URL, INFLUX_TOKEN, INFLUX_ORG, INFLUX_BUCKET) threads: Dict[str, Tuple[ClusterBalancerThread, threading.Event]] = {} warned_duplicates: set = set() + restart_backoff: Dict[str, Tuple[int, float, Any]] = {} last_idle_notice = 0.0 + + def _start(c, ev): + t = ClusterBalancerThread(c, migration_logger, ev) + t.start() + return t try: while True: try: @@ -803,20 +938,7 @@ def _handle_sigterm(*_): print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [{dup.name}] Balancing SUSPENDED: same HyperCore " f"cluster as '{group[0].name}'. Remove the duplicate entry or point it at another cluster.") warned_duplicates.add(dup.cluster_id) - for cid, (t, ev) in list(threads.items()): - c = clusters.get(cid) - # stop on removal/disable, on a credential/host change, if the thread died, or when suspended - if c is None or c.updated_at != t.cluster.updated_at or not t.is_alive() or cid in suspended: - ev.set() - del threads[cid] - for cid, c in clusters.items(): - if cid in suspended: - continue - if cid not in threads: - ev = threading.Event() - t = ClusterBalancerThread(c, migration_logger, ev) - t.start() - threads[cid] = (t, ev) + reconcile(threads, clusters, suspended, restart_backoff, _start, time.time()) if not clusters and time.time() - last_idle_notice > 300: print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] No clusters registered yet — add one in the dashboard (Settings → Clusters).") last_idle_notice = time.time() diff --git a/Balancer/cluster_registry.py b/Balancer/cluster_registry.py index 2157c49..8650f82 100644 --- a/Balancer/cluster_registry.py +++ b/Balancer/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -162,9 +177,11 @@ def _row_to_cluster(r: dict) -> Cluster: # --------------------------------------------------------------------------- def list_all(include_template: bool = False) -> list[Cluster]: - sql = f'SELECT {_COLUMNS} {_FROM}' + """The registered clusters. A removed one (Remove keeps its row, renamed '(removed ...)', so history stays + valid) is not registered any more and is left out: it showed up with an Enable button.""" + sql = f'SELECT {_COLUMNS} {_FROM} WHERE c.is_active = TRUE' if not include_template: - sql += ' WHERE c.is_template = FALSE' + sql += ' AND c.is_template = FALSE' sql += ' ORDER BY c.is_template DESC, lower(c.cluster_name)' conn = _connect() try: @@ -238,7 +255,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -270,10 +290,11 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = username: Optional[str] = None, password: Optional[str] = None, verify_tls: Optional[bool] = None, colour: Optional[str] = None, enabled: Optional[bool] = None, folder_id: Optional[str] = ..., api_version: Optional[str] = None, - timezone: Optional[str] = None) -> None: + timezone: Optional[str] = None) -> Optional[int]: """Update the given fields; password is re-encrypted only when provided (non-empty). folder_id: a folder uuid to move the cluster, None to unfile it, omitted to leave it. - timezone: an IANA name to override what the cluster reports, '' to follow the cluster again.""" + timezone: an IANA name to override what the cluster reports, '' to follow the cluster again. + Returns the number of rows changed (0: no such registered cluster), None when nothing was asked.""" sets, params = [], [] if timezone is not None: tz = timezone.strip() @@ -287,8 +308,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,13 +322,20 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: if api_version not in API_VERSIONS: raise ValueError("api_version must be auto, v1 or v2") sets.append('api_version = %s'); params.append(api_version) + if (host is not None or username is not None) and not password: + # the stored password follows the entry: pointed at another address (or user) it would be sent there by + # the next connection test and by every service's next login. Whoever moves it supplies the password. + current = get(cluster_id) + if current and ((host is not None and normalize_host(host) != current.host) + or (username is not None and username.strip() != current.username)): + raise ValueError('changing the address or the user name needs the password in the same request') if not sets: return sets.append('updated_at = NOW()') @@ -314,11 +346,15 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = conn = _connect() try: with conn.cursor() as cur: + # a removed cluster is not changed (enabling one, with no password left, made every service try an + # empty-password login each poll) cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} ' - f'WHERE cluster_id = %s AND is_template = FALSE', params) + f'WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE', params) + changed = cur.rowcount conn.commit() finally: conn.close() + return changed def delete(cluster_id: str, purge: bool = False) -> None: @@ -335,20 +371,26 @@ def delete(cluster_id: str, purge: bool = False) -> None: cur.execute('DELETE FROM config.module_toggles WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.branding WHERE cluster_id = %s', (cluster_id,)) if purge: + # children before the rows they reference: webhook deliveries and the action log point at + # recommendation events, resize advice at right-sizing rows + events = 'SELECT id FROM audit.recommendation_events WHERE cluster_id = %s' + for table in ('audit.webhook_deliveries', 'audit.action_log'): + cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s OR recommendation_event_id IN ({events})', + (cluster_id, cluster_id)) for table in ('recommendations.resize_recommendations', 'recommendations.right_sizing', 'recommendations.forecast_snapshots', 'recommendations.resource_exhaustion', - 'recommendations.cluster_health_scores', 'audit.recommendation_events', - 'audit.action_log', 'audit.webhook_deliveries'): + 'recommendations.cluster_health_scores', 'audit.recommendation_events'): cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.clusters WHERE cluster_id = %s AND is_template = FALSE', (cluster_id,)) else: - # keep the row so FK-bound history stays valid, but take it out of service + # keep the row so FK-bound history stays valid, but take it out of service (once: removing it + # again would append a second '(removed ...)') cur.execute('''UPDATE config.clusters SET enabled = FALSE, is_active = FALSE, hc_password_enc = NULL, cluster_name = cluster_name || ' (removed ' || to_char(NOW(), 'YYYY-MM-DD HH24:MI') || ')', updated_at = NOW() - WHERE cluster_id = %s AND is_template = FALSE''', (cluster_id,)) + WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE''', (cluster_id,)) conn.commit() finally: conn.close() @@ -413,15 +455,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +579,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +589,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +599,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +639,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +719,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +738,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +758,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +785,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +795,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- @@ -836,7 +890,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -851,7 +905,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/Balancer/config_db.py b/Balancer/config_db.py index 31909ef..6d7e801 100644 --- a/Balancer/config_db.py +++ b/Balancer/config_db.py @@ -15,8 +15,9 @@ Connection: PG_HOST / PG_PORT / PG_DB / PG_USER / PG_PASSWORD env vars. Graceful degradation: if PostgreSQL is unreachable, all reads fall back to -the env var value for that key (or the hardcoded default). Writes are -silently dropped with a warning log. The service continues operating normally. +the env var value for that key (or the hardcoded default), and a stored value +that cannot be cast falls back for that key only. save() drops a write with a +warning; save_many() (the settings API) raises so the caller can report it. On first run, values are seeded from environment variables (falling back to hardcoded defaults). After that, env vars are ignored for keys the user has @@ -74,14 +75,48 @@ 'STALE_SECONDS': ('SC_DASHBOARD_STALE_SECONDS', 120, 'int'), } +# key → (min, max) a stored value must lie within; the same ranges as the settings sliders +# (CTRL_GROUPS in dashboard/static/index.html), checked again by validate() on every write +RANGES = { + 'VERBOSITY': (0, 3), + 'AVG_WINDOW_MINUTES': (1, 30), + 'SAMPLE_INTERVAL_SECONDS': (10, 300), + 'RAM_LIMIT_PERCENT': (50, 100), + 'RAM_UPPER_THRESHOLD_PERCENT': (10, 100), + 'CPU_UPPER_THRESHOLD_PERCENT': (10, 100), + 'MAX_VCPU_RATIO': (0.5, 8.0), + 'VM_MOVE_COOLDOWN_MINUTES': (0, 120), + 'MIGRATION_COOLDOWN_MINUTES': (0, 60), + 'CPU_TARGET_TOLERANCE_PERCENT': (1, 20), + 'PREDICTIVE_INTERVAL_SECONDS': (3600, 86400), + 'PREDICTIVE_LEAD_TIME_HOURS': (1, 24), + 'PREDICTIVE_THRESHOLD': (50, 100), + 'PREDICTIVE_MIN_HISTORY_HOURS': (24, 720), + 'PREDICTIVE_LOOKBACK_DAYS': (7, 365), + 'PREDICTIVE_MAX_WORKERS': (1, 16), + 'PREDICTIVE_RESERVATION_MINUTES': (0, 120), + 'POLL_INTERVAL': (10, 120), + 'SLOW_POLL_INTERVAL': (60, 3600), + 'INFLUX_WRITE_RETRIES': (1, 10), + 'INFLUX_RETRY_DELAY': (1, 30), + 'STALE_SECONDS': (30, 600), +} + +_TRUE, _FALSE = ('true', '1', 'yes', 'y'), ('false', '0', 'no', 'n', '') + # --------------------------------------------------------------------------- # type helpers # --------------------------------------------------------------------------- def _cast(value: str, type_hint: str) -> Any: + """Stored text → Python value. Raises ValueError for text that is not a value of the type + (an emptied number field once stored 'None'; a bool reading 'None' was silently false).""" if type_hint == 'bool': - return str(value).lower() in ('true', '1', 'yes', 'y') + v = str(value).strip().lower() + if v in _TRUE or v in _FALSE: + return v in _TRUE + raise ValueError(f'not a boolean: {value!r}') if type_hint == 'int': return int(float(value)) # float() first handles "30.0" edge case if type_hint == 'float': @@ -95,10 +130,47 @@ def _serialize(value: Any, type_hint: str) -> str: if type_hint == 'list': return ','.join(str(v) for v in value) if isinstance(value, list) else str(value) if type_hint == 'bool': + if isinstance(value, str): # the string 'false' is truthy: it was stored as true + value = _cast(value, 'bool') return 'true' if value else 'false' return str(value) +def validate(key: str, value: Any) -> Any: + """The typed value `value` stands for, or ValueError: unknown key, null, not castable to the + key's type, not a finite number, or outside RANGES. Run on every value before it is stored, + since one value no reader can cast used to cost the whole cluster its settings.""" + if key not in TUNABLES: + raise ValueError(f'unknown setting {key}') + if value is None: + raise ValueError(f'{key}: a value is required') + type_hint = TUNABLES[key][2] + if type_hint in ('int', 'float') and (isinstance(value, bool) or (isinstance(value, str) and not value.strip())): + raise ValueError(f'{key}: a number is required') + if type_hint == 'list' and not isinstance(value, (str, list)): + raise ValueError(f'{key}: a comma-separated list is required') + try: + typed = _cast(_serialize(value, type_hint), type_hint) + except (TypeError, ValueError, OverflowError): + raise ValueError(f'{key}: {value!r} is not a valid {type_hint}') from None + if type_hint in ('int', 'float'): + if typed != typed or typed in (float('inf'), float('-inf')): + raise ValueError(f'{key}: {value!r} is not a valid {type_hint}') + lo, hi = RANGES.get(key, (None, None)) + if (lo is not None and typed < lo) or (hi is not None and typed > hi): + raise ValueError(f'{key}: {typed} is outside {lo}..{hi}') + return typed + + +def _read(key: str, raw: str, type_hint: str) -> Any: + """One stored row, cast; a value that cannot be read falls back for that key only.""" + try: + return _cast(raw, type_hint) + except (TypeError, ValueError, OverflowError): + logger.warning('config_db: stored value %r for %s is not a valid %s, using the default', raw, key, type_hint) + return _env_fallback(key) + + # --------------------------------------------------------------------------- # internal helpers # --------------------------------------------------------------------------- @@ -121,7 +193,10 @@ def _env_fallback(key: str) -> Any: return None env_var, default, type_hint = entry raw = os.getenv(env_var) - return _cast(raw, type_hint) if raw else default + try: + return _cast(raw, type_hint) if raw else default + except (TypeError, ValueError): + return default # --------------------------------------------------------------------------- @@ -144,8 +219,7 @@ def seed_from_env() -> None: try: with conn.cursor() as cur: for key, (env_var, default, type_hint) in TUNABLES.items(): - raw_env = os.getenv(env_var) or None - value = _cast(raw_env, type_hint) if raw_env is not None else default + value = _env_fallback(key) cur.execute( '''INSERT INTO config.tunables (cluster_id, key, value, type) VALUES (%s, %s, %s, %s) @@ -196,7 +270,7 @@ def get(key: str, cluster_id: str = TEMPLATE_CLUSTER_ID) -> Any: conn.close() if row is None: return _env_fallback(key) - return _cast(row[0], row[1]) + return _read(key, row[0], row[1]) except Exception as exc: logger.warning('config_db: PostgreSQL unavailable for get(%s), using env fallback: %s', key, exc) return _env_fallback(key) @@ -216,7 +290,7 @@ def get_all(cluster_id: str = TEMPLATE_CLUSTER_ID) -> dict: rows = cur.fetchall() finally: conn.close() - return {r[0]: _cast(r[1], r[2]) for r in rows} + return {r[0]: _read(r[0], r[1], r[2]) for r in rows} except Exception as exc: logger.warning('config_db: PostgreSQL unavailable for get_all(), using env fallback: %s', exc) return {k: _env_fallback(k) for k in TUNABLES} @@ -247,28 +321,29 @@ def save(key: str, value: Any, cluster_id: str = TEMPLATE_CLUSTER_ID) -> None: def save_many(updates: dict, cluster_id: str = TEMPLATE_CLUSTER_ID) -> None: - """Upsert multiple tunables in one transaction. Unknown keys are silently skipped.""" + """Upsert multiple tunables in one transaction. Unknown keys are skipped; callers validate() + first. Raises when the write fails, so nobody answers 'saved' for a change that was dropped.""" with _lock: + conn = _connect() try: - conn = _connect() - try: - with conn.cursor() as cur: - for key, value in updates.items(): - if key not in TUNABLES: - continue - _, _, type_hint = TUNABLES[key] - cur.execute( - '''INSERT INTO config.tunables (cluster_id, key, value, type, updated_at) - VALUES (%s, %s, %s, %s, NOW()) - ON CONFLICT (cluster_id, key) DO UPDATE - SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at''', - (cluster_id, key, _serialize(value, type_hint), type_hint), - ) - conn.commit() - finally: - conn.close() - except Exception as exc: - logger.warning('config_db: PostgreSQL unavailable for save_many(), changes dropped: %s', exc) + with conn.cursor() as cur: + for key, value in updates.items(): + if key not in TUNABLES: + continue + _, _, type_hint = TUNABLES[key] + cur.execute( + '''INSERT INTO config.tunables (cluster_id, key, value, type, updated_at) + VALUES (%s, %s, %s, %s, NOW()) + ON CONFLICT (cluster_id, key) DO UPDATE + SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at''', + (cluster_id, key, _serialize(value, type_hint), type_hint), + ) + conn.commit() + except Exception: + logger.warning('config_db: save_many() for %s failed, nothing stored', cluster_id, exc_info=True) + raise + finally: + conn.close() def get_with_meta(cluster_id: str = TEMPLATE_CLUSTER_ID) -> list: @@ -289,7 +364,7 @@ def get_with_meta(cluster_id: str = TEMPLATE_CLUSTER_ID) -> list: finally: conn.close() return [ - {'key': r[0], 'value': _cast(r[1], r[2]), 'type': r[2], 'updated_at': str(r[3])} + {'key': r[0], 'value': _read(r[0], r[1], r[2]), 'type': r[2], 'updated_at': str(r[3])} for r in rows ] except Exception as exc: diff --git a/Balancer/constraints.txt b/Balancer/constraints.txt new file mode 100644 index 0000000..c9c74ef --- /dev/null +++ b/Balancer/constraints.txt @@ -0,0 +1,35 @@ +# Every package of the working Balancer image, transitive ones included (pip freeze, 2026-11-22, release 1.8.1). +# requirements.txt says what the service needs; this file keeps a rebuild months from now on the +# versions it was tested with (the Dockerfile installs with -c). Regenerate after changing requirements: +# docker run --rm --entrypoint pip freeze +certifi==2026.11.20 +cffi==2.1.1 +charset-normalizer==3.5.2 +cmdstanpy==1.3.2 +contourpy==1.3.3 +cryptography==42.0.8 +cycler==0.12.1 +fonttools==4.68.0 +holidays==0.109 +idna==3.20 +influxdb-client==1.50.0 +kiwisolver==1.5.1 +matplotlib==3.11.2 +numpy==2.4.6 +packaging==26.3 +pandas==3.0.6 +pillow==13.0.0 +prophet==1.5.0 +psycopg2-binary==2.9.13 +pycparser==3.12 +pyparsing==3.3.3 +python-dateutil==2.9.0.post0 +python-dotenv==1.2.4 +reactivex==6.1.1 +requests==2.34.2 +six==1.17.0 +stanio==0.5.1 +tqdm==4.70.1 +typing_extensions==4.16.0 +tzdata==2025.2 +urllib3==2.8.0 diff --git a/Balancer/hypercore_session.py b/Balancer/hypercore_session.py index dc09ac0..3ef752f 100644 --- a/Balancer/hypercore_session.py +++ b/Balancer/hypercore_session.py @@ -26,12 +26,16 @@ from typing import Callable, Optional import requests +from urllib3.exceptions import ConnectTimeoutError, NewConnectionError import cluster_registry log = logging.getLogger('hypercore_session') TRANSPORT_ERRORS = (requests.exceptions.ConnectionError, requests.exceptions.Timeout) # SSLError is a ConnectionError +# methods HyperCore may receive twice without harm; anything else (a POST that starts a migration, a clone, a new VM) +# is re-sent only when the first attempt provably never reached the node +SAFE_TO_RESEND = frozenset({'GET', 'HEAD', 'OPTIONS'}) class ClusterUnreachable(requests.exceptions.ConnectionError): @@ -76,6 +80,7 @@ def __init__(self, cluster_id: Optional[str], username: str, password: str, veri self.session.verify = self.verify self.host: Optional[str] = self._pinned self.logged_in_at = 0.0 + self.generation = 0 # +1 per successful login: lets a thread see that another one already logged in again self.lock = threading.RLock() if not self.verify: import urllib3 @@ -134,6 +139,7 @@ def login(self, exclude: Optional[str] = None) -> str: attempts.append((h, f'HTTP {r.status_code}')) continue self.host, self.logged_in_at = h, time.monotonic() + self.generation += 1 if attempts: self._log(f'{self.service}: node(s) not answering: ' + '; '.join(f'{a}: {e}' for a, e in attempts)) if previous and previous != h: @@ -177,28 +183,47 @@ def close(self) -> None: def request(self, method: str, path: str, **kw) -> requests.Response: """One REST call on the node in use. A 401 means the session expired: log in again on the same node and retry once. A transport failure means the node is gone: log in on - another candidate and retry once there. Raises ClusterUnreachable / AuthFailed.""" + another candidate and retry once there. Raises ClusterUnreachable / AuthFailed. + + Only GET/HEAD/OPTIONS are re-sent after any transport failure. Other methods are re-sent + only when the request never left (connection refused, connect timeout); a read timeout or + a dropped connection after sending may mean HyperCore accepted it, so that error goes to + the caller instead of a second (or third) migration, clone or VM.""" kw.setdefault('timeout', self.timeout) + resend_any = method.upper() in SAFE_TO_RESEND self.ensure() - host = self.host + host, generation = self.host, self.generation try: try: resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + raise # a pooled keep-alive connection the node already closed ("Remote end closed connection # without response") is no dead node: once more on the same node, on a fresh connection self._log(f'{self.service}: {host} dropped the connection ({_short(e)}); retrying there once') resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + self._log(f'{self.service}: {method} {path} on {host} failed after sending ({_short(e)}); not re-sent') + raise self._log(f'{self.service}: {host} not answering ({_short(e)}); trying another node') with self.lock: - self.logged_in_at = 0.0 - self.login(exclude=host) + if self.generation == generation: # else another thread already moved to a working node + self.logged_in_at = 0.0 + self.login(exclude=host) + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) if resp.status_code == 401: with self.lock: - self.logout() - self.login() + # six threads seeing the same expiry make one new login, and no thread logs out the session + # another thread has just made + if self.generation == generation: + self.logout() + self.login() + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) return resp @@ -214,6 +239,17 @@ def get_json(self, path: str, **kw): return resp.json() +def _not_sent(e: BaseException) -> bool: + """True when the request provably never reached the node: the TCP connection could not be made + (refused, unreachable, DNS) or timed out while connecting.""" + if isinstance(e, requests.exceptions.ConnectTimeout): + return True + if isinstance(e, requests.exceptions.ConnectionError) and e.args: + reason = getattr(e.args[0], 'reason', e.args[0]) + return isinstance(reason, (NewConnectionError, ConnectTimeoutError)) + return False + + def _short(e: BaseException) -> str: s = str(e) if isinstance(e, requests.exceptions.SSLError): diff --git a/Balancer/predictive_engine.py b/Balancer/predictive_engine.py index c0aee2d..7a3ac6e 100644 --- a/Balancer/predictive_engine.py +++ b/Balancer/predictive_engine.py @@ -287,9 +287,11 @@ def _run_forecast(vms, nodes, forecast_hours, lookback_days, min_history_hours, if predicted_node_loads[node_uuid] <= threshold: break # node is now predicted safe — stop evicting - # re-sort targets each iteration so we always pick the least-loaded one + # re-sort targets each iteration so we always pick the least-loaded one; never a node + # that may not run VMs (witness, maintenance) or is offline: empty, it would look ideal target_nodes = sorted( - [n for n in nodes if n['uuid'] != node_uuid], + [n for n in nodes if n['uuid'] != node_uuid + and n.get('allowRunningVMs', True) and n.get('networkStatus', 'ONLINE') == 'ONLINE'], key=lambda n: predicted_node_loads.get(n['uuid'], 100.0) ) diff --git a/Collector/Dockerfile b/Collector/Dockerfile index fd6a50b..525eea3 100644 --- a/Collector/Dockerfile +++ b/Collector/Dockerfile @@ -1,7 +1,10 @@ -FROM python:3.11-slim +# the Debian release is named: package names (apt) differ between releases, and a rebuild must not +# move to the next one unasked +FROM python:3.11-slim-trixie WORKDIR /app -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY requirements.txt constraints.txt ./ +# constraints.txt: every transitive package at the version this release was tested with +RUN pip install --no-cache-dir -r requirements.txt -c constraints.txt COPY collector.py . COPY config_db.py . COPY cluster_registry.py . diff --git a/Collector/cluster_registry.py b/Collector/cluster_registry.py index 2157c49..8650f82 100644 --- a/Collector/cluster_registry.py +++ b/Collector/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -162,9 +177,11 @@ def _row_to_cluster(r: dict) -> Cluster: # --------------------------------------------------------------------------- def list_all(include_template: bool = False) -> list[Cluster]: - sql = f'SELECT {_COLUMNS} {_FROM}' + """The registered clusters. A removed one (Remove keeps its row, renamed '(removed ...)', so history stays + valid) is not registered any more and is left out: it showed up with an Enable button.""" + sql = f'SELECT {_COLUMNS} {_FROM} WHERE c.is_active = TRUE' if not include_template: - sql += ' WHERE c.is_template = FALSE' + sql += ' AND c.is_template = FALSE' sql += ' ORDER BY c.is_template DESC, lower(c.cluster_name)' conn = _connect() try: @@ -238,7 +255,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -270,10 +290,11 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = username: Optional[str] = None, password: Optional[str] = None, verify_tls: Optional[bool] = None, colour: Optional[str] = None, enabled: Optional[bool] = None, folder_id: Optional[str] = ..., api_version: Optional[str] = None, - timezone: Optional[str] = None) -> None: + timezone: Optional[str] = None) -> Optional[int]: """Update the given fields; password is re-encrypted only when provided (non-empty). folder_id: a folder uuid to move the cluster, None to unfile it, omitted to leave it. - timezone: an IANA name to override what the cluster reports, '' to follow the cluster again.""" + timezone: an IANA name to override what the cluster reports, '' to follow the cluster again. + Returns the number of rows changed (0: no such registered cluster), None when nothing was asked.""" sets, params = [], [] if timezone is not None: tz = timezone.strip() @@ -287,8 +308,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,13 +322,20 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: if api_version not in API_VERSIONS: raise ValueError("api_version must be auto, v1 or v2") sets.append('api_version = %s'); params.append(api_version) + if (host is not None or username is not None) and not password: + # the stored password follows the entry: pointed at another address (or user) it would be sent there by + # the next connection test and by every service's next login. Whoever moves it supplies the password. + current = get(cluster_id) + if current and ((host is not None and normalize_host(host) != current.host) + or (username is not None and username.strip() != current.username)): + raise ValueError('changing the address or the user name needs the password in the same request') if not sets: return sets.append('updated_at = NOW()') @@ -314,11 +346,15 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = conn = _connect() try: with conn.cursor() as cur: + # a removed cluster is not changed (enabling one, with no password left, made every service try an + # empty-password login each poll) cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} ' - f'WHERE cluster_id = %s AND is_template = FALSE', params) + f'WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE', params) + changed = cur.rowcount conn.commit() finally: conn.close() + return changed def delete(cluster_id: str, purge: bool = False) -> None: @@ -335,20 +371,26 @@ def delete(cluster_id: str, purge: bool = False) -> None: cur.execute('DELETE FROM config.module_toggles WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.branding WHERE cluster_id = %s', (cluster_id,)) if purge: + # children before the rows they reference: webhook deliveries and the action log point at + # recommendation events, resize advice at right-sizing rows + events = 'SELECT id FROM audit.recommendation_events WHERE cluster_id = %s' + for table in ('audit.webhook_deliveries', 'audit.action_log'): + cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s OR recommendation_event_id IN ({events})', + (cluster_id, cluster_id)) for table in ('recommendations.resize_recommendations', 'recommendations.right_sizing', 'recommendations.forecast_snapshots', 'recommendations.resource_exhaustion', - 'recommendations.cluster_health_scores', 'audit.recommendation_events', - 'audit.action_log', 'audit.webhook_deliveries'): + 'recommendations.cluster_health_scores', 'audit.recommendation_events'): cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.clusters WHERE cluster_id = %s AND is_template = FALSE', (cluster_id,)) else: - # keep the row so FK-bound history stays valid, but take it out of service + # keep the row so FK-bound history stays valid, but take it out of service (once: removing it + # again would append a second '(removed ...)') cur.execute('''UPDATE config.clusters SET enabled = FALSE, is_active = FALSE, hc_password_enc = NULL, cluster_name = cluster_name || ' (removed ' || to_char(NOW(), 'YYYY-MM-DD HH24:MI') || ')', updated_at = NOW() - WHERE cluster_id = %s AND is_template = FALSE''', (cluster_id,)) + WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE''', (cluster_id,)) conn.commit() finally: conn.close() @@ -413,15 +455,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +579,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +589,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +599,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +639,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +719,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +738,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +758,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +785,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +795,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- @@ -836,7 +890,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -851,7 +905,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/Collector/collector.py b/Collector/collector.py index 4ac5776..9260422 100644 --- a/Collector/collector.py +++ b/Collector/collector.py @@ -246,7 +246,51 @@ def collect_fast(cid, nodes, vms, vm_stats, node_info_map): return points, vm_info_map -def collect_slow(cid, hc, node_info_map): +# a condition whose fields did not change is written again after this long, so the dashboard's +# active-alert query (the last point of the past hour) and history (distinct set/clear times plus +# the latest point) read exactly what they did when every condition was written every slow poll +CONDITION_HEARTBEAT_SECONDS = 1800 + + +def condition_points(cid, conditions, state=None, now=None): + """condition_metrics points for the user-visible conditions: each SET or not (the dashboard + takes the latest point per condition, so one that clears must be written as value=false or it + would stay lit). lastSetTime / lastClearTime (ms) give each episode HyperCore's exact start and + end. With `state` (a dict kept per cluster between polls) a condition is written only when one + of its fields changed or its last point is CONDITION_HEARTBEAT_SECONDS old; writing every + condition every 300 s made the alert-history queries slow on real clusters.""" + now = time.time() if now is None else now + points = [] + for cond in conditions or []: + if not cond.get('userVisible', False): + continue + tags = { + 'condition_name': cond.get('name', 'unknown'), 'node_uuid': cond.get('nodeUUID', ''), + 'node_lan_ip': cond.get('nodeLANIP', ''), 'severity': cond.get('severity', 'INFO'), + } + fields = { + 'value': bool(cond.get('value', False)), 'is_ok': bool(cond.get('isOK', True)), + 'is_expired': bool(cond.get('isExpired', False)), 'description': cond.get('description', ''), + 'last_set_time': int(cond.get('lastSetTime') or 0), 'last_clear_time': int(cond.get('lastClearTime') or 0), + 'tags': ','.join(str(t) for t in (cond.get('tags') or [])), + } + if state is not None: + key = (tags['condition_name'], tags['node_uuid']) + sig = (tuple(sorted(tags.items())), tuple(sorted(fields.items()))) + prev = state.get(key) + if prev and prev[0] == sig and now - prev[1] < CONDITION_HEARTBEAT_SECONDS: + continue + state[key] = (sig, now) + p = Point("condition_metrics").tag("cluster_id", cid) + for k, v in tags.items(): + p = p.tag(k, v) + for k, v in fields.items(): + p = p.field(k, v) + points.append(p) + return points + + +def collect_slow(cid, hc, node_info_map, cond_state=None): """Collects low-frequency data: snapshots, replication, cluster info, conditions.""" points = [] @@ -306,26 +350,7 @@ def collect_slow(cid, hc, node_info_map): # ========================================================================= # conditions — cluster health alerts # ========================================================================= - conditions = fetch_safe(hc, "/Condition") - for cond in conditions: - # every user-visible condition, SET or not: the dashboard takes the latest point per - # condition, so one that clears must be written as value=false or it would stay lit. - # lastSetTime / lastClearTime (ms) give each episode HyperCore's exact start and end. - if not cond.get('userVisible', False): - continue - p = Point("condition_metrics").tag("cluster_id", cid) \ - .tag("condition_name", cond.get('name', 'unknown')) \ - .tag("node_uuid", cond.get('nodeUUID', '')) \ - .tag("node_lan_ip", cond.get('nodeLANIP', '')) \ - .tag("severity", cond.get('severity', 'INFO')) \ - .field("value", bool(cond.get('value', False))) \ - .field("is_ok", bool(cond.get('isOK', True))) \ - .field("is_expired", bool(cond.get('isExpired', False))) \ - .field("description", cond.get('description', '')) \ - .field("last_set_time", int(cond.get('lastSetTime') or 0)) \ - .field("last_clear_time", int(cond.get('lastClearTime') or 0)) \ - .field("tags", ','.join(str(t) for t in (cond.get('tags') or []))) - points.append(p) + points.extend(condition_points(cid, fetch_safe(hc, "/Condition"), cond_state)) return points @@ -381,6 +406,7 @@ def __init__(self, cluster, write_api, stop_event): self._seen_moves: set[str] = set() self._nodes_sig = None # last node list stored in the registry (uuid, ip, status, ...) self._nodes_stored_at = 0.0 + self._cond_state: dict = {} # (condition, node) -> (fields last written, when) def log(self, msg): print(f"[{_ts()}] [{self.cluster.name}] {msg}") @@ -450,6 +476,7 @@ def run(self): write_retries = config_db.get('INFLUX_WRITE_RETRIES', self.cid) or 3 retry_delay = config_db.get('INFLUX_RETRY_DELAY', self.cid) or 5 + conditions_unwritten = False try: nodes = fetch_data(self.hc, "/Node") vms = fetch_data(self.hc, "/VirDomain") @@ -460,7 +487,8 @@ def run(self): slow_points = [] if time.time() - last_slow_poll >= slow_poll_interval: - slow_points = collect_slow(self.cid, self.hc, node_info_map) + slow_points = collect_slow(self.cid, self.hc, node_info_map, self._cond_state) + conditions_unwritten = True last_slow_poll = time.time() # pick up a changed API switch and (unless v1 is forced) re-probe REST v2 fresh = cluster_registry.get(self.cid) @@ -481,6 +509,7 @@ def run(self): if self.cluster.uses_v2: self._poll_tasks(all_points) if write_with_retry(self.write_api, INFLUX_BUCKET, all_points, write_retries, retry_delay): + conditions_unwritten = False slow_note = f" + {len(slow_points)} slow" if slow_points else "" self.log(f"Wrote {len(all_points)} datapoints ({len(fast_points)} fast{slow_note}).") @@ -504,6 +533,8 @@ def run(self): except Exception as e: self.log(f"Unexpected Error: {e}") cluster_registry.mark_error(self.cid, str(e)) + if conditions_unwritten: + self._cond_state.clear() # nothing was stored: write every condition next slow poll self.stop.wait(poll_interval) @@ -544,6 +575,11 @@ def main(): ev.set() del workers[cid] for cid, c in clusters.items(): + # a worker that ended on its own (an exception nothing caught) is replaced, as the + # balancer does: without this its cluster stays without metrics until a restart + if cid in workers and not workers[cid][0].is_alive(): + print(f"[{_ts()}] Collector for {c.name} stopped unexpectedly; starting it again.") + del workers[cid] if cid not in workers: ev = threading.Event() w = ClusterWorker(c, write_api, ev) diff --git a/Collector/config_db.py b/Collector/config_db.py index 31909ef..6d7e801 100644 --- a/Collector/config_db.py +++ b/Collector/config_db.py @@ -15,8 +15,9 @@ Connection: PG_HOST / PG_PORT / PG_DB / PG_USER / PG_PASSWORD env vars. Graceful degradation: if PostgreSQL is unreachable, all reads fall back to -the env var value for that key (or the hardcoded default). Writes are -silently dropped with a warning log. The service continues operating normally. +the env var value for that key (or the hardcoded default), and a stored value +that cannot be cast falls back for that key only. save() drops a write with a +warning; save_many() (the settings API) raises so the caller can report it. On first run, values are seeded from environment variables (falling back to hardcoded defaults). After that, env vars are ignored for keys the user has @@ -74,14 +75,48 @@ 'STALE_SECONDS': ('SC_DASHBOARD_STALE_SECONDS', 120, 'int'), } +# key → (min, max) a stored value must lie within; the same ranges as the settings sliders +# (CTRL_GROUPS in dashboard/static/index.html), checked again by validate() on every write +RANGES = { + 'VERBOSITY': (0, 3), + 'AVG_WINDOW_MINUTES': (1, 30), + 'SAMPLE_INTERVAL_SECONDS': (10, 300), + 'RAM_LIMIT_PERCENT': (50, 100), + 'RAM_UPPER_THRESHOLD_PERCENT': (10, 100), + 'CPU_UPPER_THRESHOLD_PERCENT': (10, 100), + 'MAX_VCPU_RATIO': (0.5, 8.0), + 'VM_MOVE_COOLDOWN_MINUTES': (0, 120), + 'MIGRATION_COOLDOWN_MINUTES': (0, 60), + 'CPU_TARGET_TOLERANCE_PERCENT': (1, 20), + 'PREDICTIVE_INTERVAL_SECONDS': (3600, 86400), + 'PREDICTIVE_LEAD_TIME_HOURS': (1, 24), + 'PREDICTIVE_THRESHOLD': (50, 100), + 'PREDICTIVE_MIN_HISTORY_HOURS': (24, 720), + 'PREDICTIVE_LOOKBACK_DAYS': (7, 365), + 'PREDICTIVE_MAX_WORKERS': (1, 16), + 'PREDICTIVE_RESERVATION_MINUTES': (0, 120), + 'POLL_INTERVAL': (10, 120), + 'SLOW_POLL_INTERVAL': (60, 3600), + 'INFLUX_WRITE_RETRIES': (1, 10), + 'INFLUX_RETRY_DELAY': (1, 30), + 'STALE_SECONDS': (30, 600), +} + +_TRUE, _FALSE = ('true', '1', 'yes', 'y'), ('false', '0', 'no', 'n', '') + # --------------------------------------------------------------------------- # type helpers # --------------------------------------------------------------------------- def _cast(value: str, type_hint: str) -> Any: + """Stored text → Python value. Raises ValueError for text that is not a value of the type + (an emptied number field once stored 'None'; a bool reading 'None' was silently false).""" if type_hint == 'bool': - return str(value).lower() in ('true', '1', 'yes', 'y') + v = str(value).strip().lower() + if v in _TRUE or v in _FALSE: + return v in _TRUE + raise ValueError(f'not a boolean: {value!r}') if type_hint == 'int': return int(float(value)) # float() first handles "30.0" edge case if type_hint == 'float': @@ -95,10 +130,47 @@ def _serialize(value: Any, type_hint: str) -> str: if type_hint == 'list': return ','.join(str(v) for v in value) if isinstance(value, list) else str(value) if type_hint == 'bool': + if isinstance(value, str): # the string 'false' is truthy: it was stored as true + value = _cast(value, 'bool') return 'true' if value else 'false' return str(value) +def validate(key: str, value: Any) -> Any: + """The typed value `value` stands for, or ValueError: unknown key, null, not castable to the + key's type, not a finite number, or outside RANGES. Run on every value before it is stored, + since one value no reader can cast used to cost the whole cluster its settings.""" + if key not in TUNABLES: + raise ValueError(f'unknown setting {key}') + if value is None: + raise ValueError(f'{key}: a value is required') + type_hint = TUNABLES[key][2] + if type_hint in ('int', 'float') and (isinstance(value, bool) or (isinstance(value, str) and not value.strip())): + raise ValueError(f'{key}: a number is required') + if type_hint == 'list' and not isinstance(value, (str, list)): + raise ValueError(f'{key}: a comma-separated list is required') + try: + typed = _cast(_serialize(value, type_hint), type_hint) + except (TypeError, ValueError, OverflowError): + raise ValueError(f'{key}: {value!r} is not a valid {type_hint}') from None + if type_hint in ('int', 'float'): + if typed != typed or typed in (float('inf'), float('-inf')): + raise ValueError(f'{key}: {value!r} is not a valid {type_hint}') + lo, hi = RANGES.get(key, (None, None)) + if (lo is not None and typed < lo) or (hi is not None and typed > hi): + raise ValueError(f'{key}: {typed} is outside {lo}..{hi}') + return typed + + +def _read(key: str, raw: str, type_hint: str) -> Any: + """One stored row, cast; a value that cannot be read falls back for that key only.""" + try: + return _cast(raw, type_hint) + except (TypeError, ValueError, OverflowError): + logger.warning('config_db: stored value %r for %s is not a valid %s, using the default', raw, key, type_hint) + return _env_fallback(key) + + # --------------------------------------------------------------------------- # internal helpers # --------------------------------------------------------------------------- @@ -121,7 +193,10 @@ def _env_fallback(key: str) -> Any: return None env_var, default, type_hint = entry raw = os.getenv(env_var) - return _cast(raw, type_hint) if raw else default + try: + return _cast(raw, type_hint) if raw else default + except (TypeError, ValueError): + return default # --------------------------------------------------------------------------- @@ -144,8 +219,7 @@ def seed_from_env() -> None: try: with conn.cursor() as cur: for key, (env_var, default, type_hint) in TUNABLES.items(): - raw_env = os.getenv(env_var) or None - value = _cast(raw_env, type_hint) if raw_env is not None else default + value = _env_fallback(key) cur.execute( '''INSERT INTO config.tunables (cluster_id, key, value, type) VALUES (%s, %s, %s, %s) @@ -196,7 +270,7 @@ def get(key: str, cluster_id: str = TEMPLATE_CLUSTER_ID) -> Any: conn.close() if row is None: return _env_fallback(key) - return _cast(row[0], row[1]) + return _read(key, row[0], row[1]) except Exception as exc: logger.warning('config_db: PostgreSQL unavailable for get(%s), using env fallback: %s', key, exc) return _env_fallback(key) @@ -216,7 +290,7 @@ def get_all(cluster_id: str = TEMPLATE_CLUSTER_ID) -> dict: rows = cur.fetchall() finally: conn.close() - return {r[0]: _cast(r[1], r[2]) for r in rows} + return {r[0]: _read(r[0], r[1], r[2]) for r in rows} except Exception as exc: logger.warning('config_db: PostgreSQL unavailable for get_all(), using env fallback: %s', exc) return {k: _env_fallback(k) for k in TUNABLES} @@ -247,28 +321,29 @@ def save(key: str, value: Any, cluster_id: str = TEMPLATE_CLUSTER_ID) -> None: def save_many(updates: dict, cluster_id: str = TEMPLATE_CLUSTER_ID) -> None: - """Upsert multiple tunables in one transaction. Unknown keys are silently skipped.""" + """Upsert multiple tunables in one transaction. Unknown keys are skipped; callers validate() + first. Raises when the write fails, so nobody answers 'saved' for a change that was dropped.""" with _lock: + conn = _connect() try: - conn = _connect() - try: - with conn.cursor() as cur: - for key, value in updates.items(): - if key not in TUNABLES: - continue - _, _, type_hint = TUNABLES[key] - cur.execute( - '''INSERT INTO config.tunables (cluster_id, key, value, type, updated_at) - VALUES (%s, %s, %s, %s, NOW()) - ON CONFLICT (cluster_id, key) DO UPDATE - SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at''', - (cluster_id, key, _serialize(value, type_hint), type_hint), - ) - conn.commit() - finally: - conn.close() - except Exception as exc: - logger.warning('config_db: PostgreSQL unavailable for save_many(), changes dropped: %s', exc) + with conn.cursor() as cur: + for key, value in updates.items(): + if key not in TUNABLES: + continue + _, _, type_hint = TUNABLES[key] + cur.execute( + '''INSERT INTO config.tunables (cluster_id, key, value, type, updated_at) + VALUES (%s, %s, %s, %s, NOW()) + ON CONFLICT (cluster_id, key) DO UPDATE + SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at''', + (cluster_id, key, _serialize(value, type_hint), type_hint), + ) + conn.commit() + except Exception: + logger.warning('config_db: save_many() for %s failed, nothing stored', cluster_id, exc_info=True) + raise + finally: + conn.close() def get_with_meta(cluster_id: str = TEMPLATE_CLUSTER_ID) -> list: @@ -289,7 +364,7 @@ def get_with_meta(cluster_id: str = TEMPLATE_CLUSTER_ID) -> list: finally: conn.close() return [ - {'key': r[0], 'value': _cast(r[1], r[2]), 'type': r[2], 'updated_at': str(r[3])} + {'key': r[0], 'value': _read(r[0], r[1], r[2]), 'type': r[2], 'updated_at': str(r[3])} for r in rows ] except Exception as exc: diff --git a/Collector/constraints.txt b/Collector/constraints.txt new file mode 100644 index 0000000..f19efff --- /dev/null +++ b/Collector/constraints.txt @@ -0,0 +1,19 @@ +# Every package of the working Collector image, transitive ones included (pip freeze, 2026-11-22, release 1.8.1). +# requirements.txt says what the service needs; this file keeps a rebuild months from now on the +# versions it was tested with (the Dockerfile installs with -c). Regenerate after changing requirements: +# docker run --rm --entrypoint pip freeze +certifi==2026.10.23 +cffi==2.1.1 +charset-normalizer==3.5.2 +cryptography==42.0.8 +idna==3.20 +influxdb-client==1.50.0 +packaging==26.3 +psycopg2-binary==2.9.13 +pycparser==3.12 +python-dateutil==4.0.0 +reactivex==6.1.0 +requests==2.34.2 +typing_extensions==4.16.0 +tzdata==2026.6 +urllib3==2.8.0 diff --git a/Collector/hypercore_session.py b/Collector/hypercore_session.py index dc09ac0..3ef752f 100644 --- a/Collector/hypercore_session.py +++ b/Collector/hypercore_session.py @@ -26,12 +26,16 @@ from typing import Callable, Optional import requests +from urllib3.exceptions import ConnectTimeoutError, NewConnectionError import cluster_registry log = logging.getLogger('hypercore_session') TRANSPORT_ERRORS = (requests.exceptions.ConnectionError, requests.exceptions.Timeout) # SSLError is a ConnectionError +# methods HyperCore may receive twice without harm; anything else (a POST that starts a migration, a clone, a new VM) +# is re-sent only when the first attempt provably never reached the node +SAFE_TO_RESEND = frozenset({'GET', 'HEAD', 'OPTIONS'}) class ClusterUnreachable(requests.exceptions.ConnectionError): @@ -76,6 +80,7 @@ def __init__(self, cluster_id: Optional[str], username: str, password: str, veri self.session.verify = self.verify self.host: Optional[str] = self._pinned self.logged_in_at = 0.0 + self.generation = 0 # +1 per successful login: lets a thread see that another one already logged in again self.lock = threading.RLock() if not self.verify: import urllib3 @@ -134,6 +139,7 @@ def login(self, exclude: Optional[str] = None) -> str: attempts.append((h, f'HTTP {r.status_code}')) continue self.host, self.logged_in_at = h, time.monotonic() + self.generation += 1 if attempts: self._log(f'{self.service}: node(s) not answering: ' + '; '.join(f'{a}: {e}' for a, e in attempts)) if previous and previous != h: @@ -177,28 +183,47 @@ def close(self) -> None: def request(self, method: str, path: str, **kw) -> requests.Response: """One REST call on the node in use. A 401 means the session expired: log in again on the same node and retry once. A transport failure means the node is gone: log in on - another candidate and retry once there. Raises ClusterUnreachable / AuthFailed.""" + another candidate and retry once there. Raises ClusterUnreachable / AuthFailed. + + Only GET/HEAD/OPTIONS are re-sent after any transport failure. Other methods are re-sent + only when the request never left (connection refused, connect timeout); a read timeout or + a dropped connection after sending may mean HyperCore accepted it, so that error goes to + the caller instead of a second (or third) migration, clone or VM.""" kw.setdefault('timeout', self.timeout) + resend_any = method.upper() in SAFE_TO_RESEND self.ensure() - host = self.host + host, generation = self.host, self.generation try: try: resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + raise # a pooled keep-alive connection the node already closed ("Remote end closed connection # without response") is no dead node: once more on the same node, on a fresh connection self._log(f'{self.service}: {host} dropped the connection ({_short(e)}); retrying there once') resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + self._log(f'{self.service}: {method} {path} on {host} failed after sending ({_short(e)}); not re-sent') + raise self._log(f'{self.service}: {host} not answering ({_short(e)}); trying another node') with self.lock: - self.logged_in_at = 0.0 - self.login(exclude=host) + if self.generation == generation: # else another thread already moved to a working node + self.logged_in_at = 0.0 + self.login(exclude=host) + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) if resp.status_code == 401: with self.lock: - self.logout() - self.login() + # six threads seeing the same expiry make one new login, and no thread logs out the session + # another thread has just made + if self.generation == generation: + self.logout() + self.login() + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) return resp @@ -214,6 +239,17 @@ def get_json(self, path: str, **kw): return resp.json() +def _not_sent(e: BaseException) -> bool: + """True when the request provably never reached the node: the TCP connection could not be made + (refused, unreachable, DNS) or timed out while connecting.""" + if isinstance(e, requests.exceptions.ConnectTimeout): + return True + if isinstance(e, requests.exceptions.ConnectionError) and e.args: + reason = getattr(e.args[0], 'reason', e.args[0]) + return isinstance(reason, (NewConnectionError, ConnectTimeoutError)) + return False + + def _short(e: BaseException) -> str: s = str(e) if isinstance(e, requests.exceptions.SSLError): diff --git a/LICENSE b/LICENSE index 939a5d7..eca14e9 100644 --- a/LICENSE +++ b/LICENSE @@ -176,7 +176,7 @@ END OF TERMS AND CONDITIONS - Copyright 2026 Scale Computing + Copyright 2026 William David van Collenburg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/NOTICE b/NOTICE index 28686c5..f6d79d8 100644 --- a/NOTICE +++ b/NOTICE @@ -1,6 +1,6 @@ HyperCore Manager -Copyright 2026 Scale Computing +Copyright 2026 William David van Collenburg -This product includes software developed for Scale Computing HyperCore -clusters. It is community-supported software, not an official Scale -Computing product. See LICENSE for terms. +Community-supported software for Scale Computing HyperCore clusters. It is +not an official Scale Computing product. Licensed under the Apache License, +Version 2.0; see LICENSE for terms. diff --git a/README.md b/README.md index 367365f..6bbfb97 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ so clusters can be added, disabled or removed independently. ### Prerequisites - A Linux host or VM (Ubuntu 22.04+ tested) with **Docker Engine 24+** and **Docker Compose v2**. - - Compose v2 is the `docker compose` (no hyphen) command. The legacy python `docker-compose` 1.29.x is **not supported** — it has known recreate bugs that break the in-app updater. On Debian/Ubuntu, install via `sudo apt install docker-compose-v2`. + - Compose v2 is the `docker compose` (no hyphen) command. The legacy python `docker-compose` 1.29.x is **not supported** — it has known recreate bugs that break the in-app updater. On Ubuntu, install via `sudo apt install docker-compose-v2`; on Debian, install Docker from Docker's own repository, which includes the `docker-compose-plugin`. - HyperCore cluster management IP and a service account with read + migration permissions. - Outbound HTTPS (TCP 443) to every node of each cluster (or fully offline — see [Dark-Site Deployment](#dark-site--air-gapped-deployment)). Backups add proxies and a share; see [Network requirements](#network-requirements). - ~2 vCPU / 4 GB RAM minimum for the core stack; more for Foresight (see [Resource Requirements](#resource-requirements)). @@ -122,7 +122,8 @@ connection in the direction listed (a stateful firewall allows the replies). | Backup proxy | Ubuntu archive or apt mirror | TCP 80 / 443 | Only on the first boot of a proxy deployed from the dashboard | | Cluster nodes | Backup share | TCP 445 | Restores, test restores, export mode, Import (HyperCore imports and exports over SMB only) | -Block 8081, 8082 and 8086 from outside the host: the dashboard reaches those containers internally. +Ports 8081, 8082 and 8086 (Foresight API, backup API, InfluxDB) are published on 127.0.0.1 only: the +dashboard reaches those containers internally. `HCM_INTERNAL_BIND` in `.env` changes that. DNS and NTP are needed as usual. The full table, the test-restore VLAN and typical layouts (MSP sites, a share on another site, a DR cluster, no internet) are in [Connectivity](docs/manual/09-connectivity.md). @@ -137,11 +138,21 @@ git clone https://github.com/wvcollenburg/hypercore-manager.git cd hypercore-manager cp .env.template .env +# the checkout's own path: the updater, the migrations and the proxy image are read from it +sed -i.bak "s|^SC_REPO_PATH=.*|SC_REPO_PATH=$(pwd)|" .env && rm .env.bak # Edit .env — replace every CHANGE_ME (HCM_SECRET_KEY, database secrets, dashboard password) docker compose up --build -d ``` +> **On a Mac:** macOS uses port 5000 for AirPlay Receiver, so `docker compose up` cannot publish the +> dashboard there. Switch AirPlay Receiver off (System Settings → General → AirDrop & Handoff) or change +> `"5000:5000"` in `docker-compose.yaml` to another host port. +> +> **The `proxy` container** is the backup proxy for a cluster the HCM host itself runs on. On a host that +> is not a VM on one of your clusters it has nothing to read and only clears the host's `/dev/nbd*` devices +> at start: stop it with `docker compose stop proxy` (deployed proxy VMs do the backup work there). + The dashboard is available at **http://localhost:5000**. Log in, and the first screen asks for your cluster: management address plus a HyperCore account. Save it and the collector, balancer and Foresight start on that cluster within a minute. Add further clusters with @@ -388,7 +399,7 @@ The dashboard includes an in-app updater that detects new releases and applies t - Releases are tagged in git as `vMAJOR.MINOR.PATCH` and announced on [GitHub Releases](https://github.com/wvcollenburg/hypercore-manager/releases). Untagged commits don't trigger update prompts — only deliberate releases do, so customers are never bombarded with "update available" for in-flight development. - Database migrations under `postgres/init/` are applied automatically on dashboard startup; every script is idempotent (`CREATE TABLE IF NOT EXISTS` and similar guards) so existing installs never lose data when a new migration ships. - The updater works against the checkout's own git origin; nothing about the repository location is built in. It recreates the application services only and leaves InfluxDB and PostgreSQL running. -- Manual update path (equivalent to clicking Apply Update in the dashboard): `git pull && docker compose up --build -d`. +- Manual update path (equivalent to clicking Apply Update in the dashboard): `git fetch --tags && git merge --ff-only v && docker compose up --build -d` (see [Installing and updating](docs/manual/08-installing-and-updating.md#updating)). --- @@ -397,10 +408,10 @@ The dashboard includes an in-app updater that detects new releases and applies t ```bash # On an internet-connected machine: docker compose build -docker save $(docker compose config --images) -o hypercore-balancer-images.tar +docker save $(docker compose config --images) -o hypercore-manager-images.tar # On the air-gapped machine: -docker load -i hypercore-balancer-images.tar +docker load -i hypercore-manager-images.tar docker compose up -d ``` @@ -443,7 +454,10 @@ Sentinel's memory limit in `docker-compose.yaml` should be sized to cover the pe ## Bring your own Grafana The stack no longer ships Grafana. If you want one, point your own instance at InfluxDB with the -Flux query language: URL `http://:8086`, organisation and bucket from `.env` +Flux query language at `http://:8086`. InfluxDB answers +on the stack host only by default: for a Grafana on another machine set `HCM_INTERNAL_BIND=0.0.0.0` in +`.env`, run `docker compose up -d influxdb`, and restrict port 8086 in a firewall in front of the host +(Docker's published ports bypass ufw). Use the organisation and bucket names from `.env` (`INFLUX_ORG`, `INFLUX_BUCKET`, long-term data in `INFLUX_LONGTERM_BUCKET`), and a read-only token created in the InfluxDB UI rather than the admin token the services use. Every measurement carries a `cluster_id` tag. @@ -550,19 +564,12 @@ carries a `cluster_id` tag. --- -## Related Projects - -| Repository | Description | -|------------|-------------| - ---- - ## Disclaimer **USE AT YOUR OWN RISK.** HyperCore Manager is community-supported software, not an official Scale Computing product. It is provided "as is" without warranty of any kind, express or implied, and without any official support or service-level commitment. Neither the authors nor Scale Computing accept responsibility or liability for any damage, data loss, downtime, or other consequences resulting from its use. Every cluster starts in dry-run; test the balancer there before switching it to live in the dashboard. ## License -Copyright (c) 2026 Scale Computing. +Copyright 2026 William David van Collenburg. Licensed under the Apache License, Version 2.0. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See [LICENSE](LICENSE) for the full text and [NOTICE](NOTICE) for attribution. diff --git a/VERSION b/VERSION index 27f9cd3..a8fdfda 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.8.0 +1.8.1 diff --git a/backup/Dockerfile b/backup/Dockerfile index 7680038..7d31557 100644 --- a/backup/Dockerfile +++ b/backup/Dockerfile @@ -1,9 +1,12 @@ -FROM python:3.12-slim +# the Debian release is named: package names (apt) differ between releases, and a rebuild must not +# move to the next one unasked +FROM python:3.12-slim-trixie WORKDIR /app -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY requirements.txt constraints.txt ./ +# constraints.txt: every transitive package at the version this release was tested with +RUN pip install --no-cache-dir -r requirements.txt -c constraints.txt COPY . . diff --git a/backup/api.py b/backup/api.py index bee3e73..11a6b41 100644 --- a/backup/api.py +++ b/backup/api.py @@ -280,8 +280,12 @@ def vmedit_changes(): cid = _cluster_arg() if not cid: return _err('cluster required') + try: + limit = int(request.args.get('limit') or 50) + except ValueError: + return _err('limit must be a whole number') return jsonify({'changes': [_vmedit_row(r) for r in vmedit.list_changes(cid, request.args.get('vm') or None, - int(request.args.get('limit') or 50))]}) + max(1, min(limit, 500)))]}) @app.post('/api/v1/vmedit/changes') @@ -451,6 +455,18 @@ def schedules(): return jsonify(rows) +def _vm_of(cid: str, vm_uuid: str): + """(the VM as HyperCore reports it, None) or (None, error response). A plan for a VM that does not exist + was accepted and then failed every night; its name is taken from HyperCore, never from the request (it is + the export prefix and the retention key).""" + try: + return jobs.client_for(cid).get_vm(vm_uuid), None + except HyperCoreError as e: + if e.status == 404 or (e.status == 0 and 'not found' in str(e).lower()): + return None, _err('that VM does not exist on the cluster', 404) + return None, _err(f'could not look up the VM on the cluster: {e}', 502) + + def _valid_time(v: str) -> str | None: try: hh, mm = (v or '').split(':') @@ -466,33 +482,36 @@ def _valid_time(v: str) -> str | None: @_require_token def schedules_add(): b = request.get_json(silent=True) or {} - cid = (b.get('cluster_id') or '').strip() + cid = str(b.get('cluster_id') or '').strip() if not cluster_registry.is_uuid(cid) or not cluster_registry.get(cid): return _err('unknown cluster') run_time = _valid_time(b.get('run_time') or cfg_module.load().default_run_time) if not run_time: return _err('run_time must be HH:MM (24h)') - for k in ('vm_uuid', 'vm_name'): - if not (b.get(k) or '').strip(): - return _err(f'{k} is required') - if not (b.get('path_uri_base') or '').strip() and not jobs.location_for_cluster(cid): - return _err("no share is assigned to this cluster's folder; an admin can add one under Settings → Shares and assign it from the folder menu") + vm_uuid = str(b.get('vm_uuid') or '').strip() + if not vm_uuid: + return _err('vm_uuid is required') + if not str(b.get('path_uri_base') or '').strip() and not jobs.location_for_cluster(cid): + return _err("no backup target is assigned to this cluster's folder; an admin adds one under Settings → Targets and assigns it with Backup target in the folder's menu in the cluster switcher") try: retention = max(1, int(b.get('retention') or cfg_module.load().default_retention)) full_every_n = max(1, int(b.get('full_every_n') or 14)) retention_days = int(b['retention_days']) if b.get('retention_days') not in (None, '', 0, '0') else None except (TypeError, ValueError): return _err('retention, full_every_n and retention_days must be numbers') - mode = (b.get('mode') or '').strip() or ('incremental' if any(p.get('vm_uuid') for p in db.get_proxies(cid, enabled_only=True)) else 'export') + mode = str(b.get('mode') or '').strip() or ('incremental' if any(p.get('vm_uuid') for p in db.get_proxies(cid, enabled_only=True)) else 'export') if mode not in ('export', 'incremental'): return _err("mode must be 'export' or 'incremental'") if mode == 'export' and _target_is_nfs(cid, b.get('path_uri_base')): return _err(jobs.smb_only_error('Export mode')) if mode == 'incremental' and not any(p.get('vm_uuid') for p in db.get_proxies(cid, enabled_only=True)): - return _err('incremental plans need a registered backup proxy for this cluster (Settings → Clusters → Proxies)') + return _err('incremental plans need a registered backup proxy for this cluster (Settings → Targets → Backup proxies)') + vm, err = _vm_of(cid, vm_uuid) + if err: + return err try: - sid = db.add_schedule(cluster_id=cid, vm_uuid=b['vm_uuid'], vm_name=b['vm_name'], - path_uri_base=(b.get('path_uri_base') or '').strip(), smb_user=b.get('smb_user'), + sid = db.add_schedule(cluster_id=cid, vm_uuid=vm['uuid'] or vm_uuid, vm_name=vm.get('name') or vm_uuid, + path_uri_base=str(b.get('path_uri_base') or '').strip(), smb_user=b.get('smb_user'), smb_password=b.get('smb_password'), prune_path=b.get('prune_path'), retention=retention, run_time=run_time, compress=bool(b.get('compress')), mode=mode, full_every_n=full_every_n, retention_days=retention_days) @@ -615,7 +634,7 @@ def _policy_fields(b: dict, creating: bool, kind: str | None = None) -> dict: `kind`: the existing policy's kind on an update.""" f = {} if creating or 'name' in b: - name = (b.get('name') or '').strip() + name = str(b.get('name') or '').strip() if not name or len(name) > 80: raise ValueError('name is required (at most 80 characters)') f['name'] = name @@ -650,7 +669,7 @@ def _policy_fields(b: dict, creating: bool, kind: str | None = None) -> dict: if k in b: f[k] = bool(b[k]) if 'full_rrule' in b: - f['full_rrule'] = recurrence.normalise_rule(b['full_rrule']) if (b['full_rrule'] or '').strip() else None + f['full_rrule'] = recurrence.normalise_rule(b['full_rrule']) if str(b['full_rrule'] or '').strip() else None if 'full_kind' in b: if b['full_kind'] not in ('real', 'synthetic'): raise ValueError("full_kind must be 'real' or 'synthetic'") @@ -724,7 +743,11 @@ def policies_preview(): return _err(str(e)) f.setdefault('timezone', b.get('timezone') or 'UTC') f.setdefault('blackouts', []) - return jsonify({'windows': recurrence.preview(f, datetime.now(timezone.utc), int(b.get('count') or 10))}) + try: + count = max(1, min(int(b.get('count') or 10), 100)) + except (TypeError, ValueError): + return _err('count must be a whole number') + return jsonify({'windows': recurrence.preview(f, datetime.now(timezone.utc), count)}) @app.post('/api/v1/policies') @@ -807,16 +830,20 @@ def policies_add_member(pid): if err: return err b = request.get_json(silent=True) or {} - cid = (b.get('cluster_id') or _cluster_arg() or '').strip() + cid = str(b.get('cluster_id') or _cluster_arg() or '').strip() if db.folder_of_cluster(cid) != (True, pol['folder_id']): return _err("the VM's cluster is not in this schedule's folder") - vm_uuid, vm_name = (b.get('vm_uuid') or '').strip(), (b.get('vm_name') or '').strip() - if not vm_uuid or not vm_name: - return _err('vm_uuid and vm_name are required') + vm_uuid = str(b.get('vm_uuid') or '').strip() + if not vm_uuid: + return _err('vm_uuid is required') if not jobs.location_for_cluster(cid): - return _err("no share is assigned to this cluster's folder; an admin can add one under Settings → Shares and assign it from the folder menu") + return _err("no backup target is assigned to this cluster's folder; an admin adds one under Settings → Targets and assigns it with Backup target in the folder's menu in the cluster switcher") if pol['kind'] == 'incremental' and not any(p.get('vm_uuid') for p in db.get_proxies(cid, enabled_only=True)): - return _err('backup schedules need a registered backup proxy on the cluster (Settings → Clusters → Proxies)') + return _err('backup schedules need a registered backup proxy on the cluster (Settings → Targets → Backup proxies)') + vm, err = _vm_of(cid, vm_uuid) + if err: + return err + vm_uuid, vm_name = vm.get('uuid') or vm_uuid, vm.get('name') or vm_uuid plan = db.plan_for_vm(cid, vm_uuid) moved_from = plan.get('policy_name') if plan and plan.get('policy_id') not in (None, pid) else None if plan is None: @@ -893,12 +920,23 @@ def _folder_source(target_cluster): return (loc['base'], loc['user'], loc['password']) if loc else None +def _scope_clusters(cluster) -> list[str]: + """The clusters whose saved locations an import onto `cluster` may reuse: those of its folder, or the + cluster alone when it has no folder.""" + if cluster is None: + return [] + if not getattr(cluster, 'folder_id', None): + return [cluster.cluster_id] + return [c['cluster_id'] for c in db.folder_clusters(cluster.folder_id)] or [cluster.cluster_id] + + def _resolve_source(b: dict, target_cluster): """(base_uri, user, password). A saved location (known_id -> schedule) keeps its credentials - server-side and is scoped to the target cluster's tenant folder, so an import can only pick - up exports that belong to the same HyperCore Manager folder. A manually typed source is used - as typed (admin-only route).""" - if not b.get('known_id') and not (b.get('source_uri') or '').strip(): + server-side; only a plan of the target cluster's own folder qualifies, and the path is scoped to + that folder's tenant directory, so an import can only pick up exports of the same HyperCore + Manager folder. A manually typed source is used as typed, with the credentials sent along + (admin-only route). Raises ValueError for a saved location outside that scope.""" + if not b.get('known_id') and not str(b.get('source_uri') or '').strip(): src = _folder_source(target_cluster) if src: return src @@ -908,11 +946,13 @@ def _resolve_source(b: dict, target_cluster): sched = db.get_schedule(int(known_id)) except (TypeError, ValueError): sched = None - if sched and (sched['path_uri_base'] or '').lower().startswith('smb://'): + if not sched or str(sched['cluster_id']) not in _scope_clusters(target_cluster): + raise ValueError("unknown saved location for this cluster's folder") + if (sched['path_uri_base'] or '').lower().startswith('smb://'): password = db.decrypt_password(sched['smb_pass_enc']) if sched['smb_pass_enc'] else '' base = f"{sched['path_uri_base'].rstrip('/')}/{jobs.tenant_slug(target_cluster)}" return base, sched['smb_user'] or '', password - return (b.get('source_uri') or '').strip(), (b.get('smb_user') or '').strip(), b.get('smb_password') or '' + return str(b.get('source_uri') or '').strip(), str(b.get('smb_user') or '').strip(), b.get('smb_password') or '' @app.get('/api/v1/import/known') @@ -922,7 +962,7 @@ def import_known(): cluster = cluster_registry.get(cid) if cid else None tenant = jobs.tenant_slug(cluster) rows = [] - for r in db.get_known_smb_locations(): + for r in db.get_known_smb_locations(_scope_clusters(cluster)): d = _ser(r) d['tenant'] = tenant d['effective_base'] = f"{r['path_uri_base'].rstrip('/')}/{tenant}" @@ -934,7 +974,10 @@ def import_known(): @_require_token def import_browse(): cid = _cluster_arg() - base, user, password = _resolve_source(request.get_json(silent=True) or {}, cluster_registry.get(cid) if cid else None) + try: + base, user, password = _resolve_source(request.get_json(silent=True) or {}, cluster_registry.get(cid) if cid else None) + except ValueError as e: + return _err(str(e)) if not base: return _err("no share is assigned to this cluster's folder") if jobs.is_nfs(base): @@ -951,19 +994,28 @@ def import_browse(): @_require_token def import_start(): b = request.get_json(silent=True) or {} - cid = (b.get('cluster_id') or '').strip() + cid = str(b.get('cluster_id') or '').strip() cluster = cluster_registry.get(cid) if cluster_registry.is_uuid(cid) else None if not cluster: return _err('unknown target cluster') - base, smb_user, smb_password = _resolve_source(b, cluster) + try: + base, smb_user, smb_password = _resolve_source(b, cluster) + except ValueError as e: + return _err(str(e)) base = base.rstrip('/') - folder = (b.get('source_folder') or '').strip().strip('/') + folder = str(b.get('source_folder') or '').strip().strip('/') + if folder and ('..' in folder or '/' in folder or '\\' in folder): + return _err('source_folder must be one folder name from the browse list') if not base: return _err('a source path is required') if jobs.is_nfs(base): return _err(jobs.smb_only_error('Import')) source_uri = f'{base}/{folder}' if folder else base - target_name = (b.get('target_name') or '').strip() + if not smb_user and '@' not in source_uri.split('//', 1)[-1].split('/', 1)[0] \ + and not jobs.under_location(source_uri, (jobs.location_for_cluster(cid) or {}).get('base')): + # the folder target's stored credentials are only ever used inside that folder's own directory + return _err("a source outside this folder's target needs smb_user and smb_password") + target_name = str(b.get('target_name') or '').strip() effective = target_name or jobs.derive_name(folder) if effective: try: @@ -985,7 +1037,7 @@ def shares_list(): def _share_body(b: dict): - return {k: (b.get(k) or '') for k in ('name', 'uri_base', 'username', 'password', 'prune_path')} + return {k: str(b.get(k) or '') for k in ('name', 'uri_base', 'username', 'password', 'prune_path')} @app.post('/api/v1/targets') @@ -1028,6 +1080,11 @@ def shares_update(sid): @app.delete('/api/v1/targets/') @_require_token def shares_delete(sid): + n = db.chains_on_target(sid) + if n: + # deleting it would set their target_id NULL: the catalogue loses where the data is, the data stays + return _err(f'{n} backup chain(s) still live on this target; delete them first (Restore points), ' + 'or assign another target to the folder and let them expire', 409) db.delete_share(sid) # folders referencing it fall back to no share (ON DELETE SET NULL) return jsonify({'ok': True}) @@ -1076,13 +1133,13 @@ def proxies_list(): @_require_token def proxies_add(): b = request.get_json(silent=True) or {} - cid = (b.get('cluster_id') or '').strip() + cid = str(b.get('cluster_id') or '').strip() if not cluster_registry.is_uuid(cid) or not cluster_registry.get(cid): return _err('unknown cluster') - url = (b.get('url') or '').strip().rstrip('/') + url = str(b.get('url') or '').strip().rstrip('/') if not url.startswith(('http://', 'https://')): return _err('url must start with http:// or https://') - name = (b.get('name') or '').strip() or url + name = str(b.get('name') or '').strip() or url fp = normalise_fingerprint(b.get('tls_fingerprint')) if url.startswith('https://') and not fp and not b.get('tls_verify'): try: @@ -1465,6 +1522,8 @@ def test_plans_vm_remove(pid): b = request.get_json(silent=True) or {} cid = str(b.get('cluster_id') or request.args.get('cluster_id') or '') vm = str(b.get('vm_uuid') or request.args.get('vm_uuid') or '') + if not cluster_registry.is_uuid(cid) or not vm: + return _err('cluster_id and vm_uuid required') return jsonify({'ok': True, 'removed': db.remove_test_plan_vm(pid, cid, vm)}) @@ -1553,6 +1612,15 @@ def chain_delete(chain_id): ch = db.get_chain(chain_id) if not ch: return _err('chain not found', 404) + work = db.chain_work(chain_id) + if work['runs'] or (ch.get('status') == 'active' and db.plan_run_active(ch.get('plan_id'))): + return _err('a backup of this chain is running; delete it when the run has finished', 409) + if work['restores']: + return _err('a restore from this chain is running; delete it when the restore has finished', 409) + if any(m.get('chain_id') == chain_id for m in flr.list_mounts()): + return _err('a point of this chain is open for file recovery; close it first', 409) + if (incremental.verify_status(chain_id) or {}).get('state') == 'running': + return _err('this chain is being verified; delete it when the verification has finished', 409) share = db.get_share(ch['target_id'], with_secret=True) if ch.get('target_id') else None if share: try: @@ -1575,6 +1643,8 @@ def _verify_view(chain_id, entry): if entry.get('result') is not None: r = entry['result'] out['ok'] = r.get('ok'); out['failed'] = r.get('failed') or {}; out['bytes'] = r.get('bytes'); out['duration_s'] = r.get('duration_s') + # points whose checksums a proxy from 0.6.5 on re-took once: written by a prune of an older proxy + out['healed'] = r.get('healed') or [] return out @@ -1630,8 +1700,10 @@ def restores_start(): policy = 'new' if policy not in ('original', 'new'): return _err('mac_policy must be new or original') - name = (b.get('target_name') or f"{chain['vm_name']}-restored").strip() - target_cid = (b.get('target_cluster_id') or chain['cluster_id']).strip() + name = str(b.get('target_name') or f"{chain['vm_name']}-restored").strip() + target_cid = str(b.get('target_cluster_id') or chain['cluster_id']).strip() + if not cluster_registry.is_uuid(target_cid): + return _err('target_cluster_id must be a cluster id') if target_cid != chain['cluster_id']: known, folder = db.folder_of_cluster(target_cid) same = known and folder is not None and folder == db.folder_of_cluster(chain['cluster_id'])[1] @@ -1680,13 +1752,19 @@ def flr_mount(): return _err(str(e), 502) +def _flr_status(e: Exception) -> int: + """A path or mount the proxy does not know is a 404 for the caller too, not a proxy failure (502).""" + text = str(e) + return 404 if 'not found' in text or 'proxy returned 404' in text else 502 + + @app.get('/api/v1/flr/mounts//ls') @_require_token def flr_ls(mid): try: return jsonify(flr.ls(mid, request.args.get('path') or '/')) except (incremental.IncrementalError, ProxyError) as e: - return _err(str(e), 404 if 'not found' in str(e) else 502) + return _err(str(e), _flr_status(e)) @app.get('/api/v1/flr/mounts//') @@ -1699,7 +1777,8 @@ def flr_download(mid, kind): try: r = flr.stream(mid, kind, dict(request.args)) except (incremental.IncrementalError, ProxyError) as e: - return _err(str(e), 404 if 'not found' in str(e) else 502) + msg = 'file not found in the restore point' if str(e) == 'proxy returned 404' else str(e) + return _err(msg, _flr_status(e)) headers = {k: v for k, v in r.headers.items() if k.lower() in ('content-length', 'content-disposition', 'content-type')} return Response(stream_with_context(r.iter_content(1 << 20)), status=r.status_code, headers=headers) @@ -1710,7 +1789,7 @@ def flr_iso(mid): """Deliver the selected files as an ISO inserted into a VM's CD-ROM. body: {paths:[...], vm_uuid}""" b = request.get_json(silent=True) or {} try: - rid = flr.start_iso_delivery(mid, [p for p in (b.get('paths') or []) if p], (b.get('vm_uuid') or '').strip(), b.get('requested_by')) + rid = flr.start_iso_delivery(mid, [p for p in (b.get('paths') or []) if p], str(b.get('vm_uuid') or '').strip(), b.get('requested_by')) except (incremental.IncrementalError, ProxyError, HyperCoreError) as e: return _err(str(e), 502) scheduler.run_iso_delivery(rid) @@ -1755,10 +1834,10 @@ def deployments_start(): ip:{mode, address, prefix, gateway, dns}, image_url, image_name, authorized_key, tz, test_vlan?}""" import deploy b = request.get_json(silent=True) or {} - cid = (b.get('cluster_id') or '').strip() + cid = str(b.get('cluster_id') or '').strip() if not cluster_registry.is_uuid(cid) or not cluster_registry.get(cid): return _err('unknown cluster') - name = (b.get('name') or '').strip() + name = str(b.get('name') or '').strip() if not name or not jobs.safe_name(name) == name: return _err('name is required and may only contain letters, digits, dots, dashes and underscores') ip = b.get('ip') or {} @@ -1767,8 +1846,8 @@ def deployments_start(): try: params = {'name': name, 'vcpu': max(1, int(b.get('vcpu') or 2)), 'mem_gb': max(1, int(b.get('mem_gb') or 2)), 'disk_gb': max(10, int(b.get('disk_gb') or 20)), 'vlan': int(b.get('vlan') or 0), 'ip': ip, - 'image_url': (b.get('image_url') or deploy.DEFAULT_IMAGE_URL).strip(), 'image_name': (b.get('image_name') or deploy.DEFAULT_IMAGE_NAME).strip(), - 'authorized_key': (b.get('authorized_key') or '').strip(), 'tz': (b.get('tz') or os.environ.get('TZ') or 'UTC'), + 'image_url': str(b.get('image_url') or deploy.DEFAULT_IMAGE_URL).strip(), 'image_name': str(b.get('image_name') or deploy.DEFAULT_IMAGE_NAME).strip(), + 'authorized_key': str(b.get('authorized_key') or '').strip(), 'tz': (b.get('tz') or os.environ.get('TZ') or 'UTC'), 'test_vlan': None if b.get('test_vlan') in (None, '') else int(b['test_vlan'])} except (TypeError, ValueError): return _err('sizes and vlan must be numbers') diff --git a/backup/cluster_registry.py b/backup/cluster_registry.py index 2157c49..8650f82 100644 --- a/backup/cluster_registry.py +++ b/backup/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -162,9 +177,11 @@ def _row_to_cluster(r: dict) -> Cluster: # --------------------------------------------------------------------------- def list_all(include_template: bool = False) -> list[Cluster]: - sql = f'SELECT {_COLUMNS} {_FROM}' + """The registered clusters. A removed one (Remove keeps its row, renamed '(removed ...)', so history stays + valid) is not registered any more and is left out: it showed up with an Enable button.""" + sql = f'SELECT {_COLUMNS} {_FROM} WHERE c.is_active = TRUE' if not include_template: - sql += ' WHERE c.is_template = FALSE' + sql += ' AND c.is_template = FALSE' sql += ' ORDER BY c.is_template DESC, lower(c.cluster_name)' conn = _connect() try: @@ -238,7 +255,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -270,10 +290,11 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = username: Optional[str] = None, password: Optional[str] = None, verify_tls: Optional[bool] = None, colour: Optional[str] = None, enabled: Optional[bool] = None, folder_id: Optional[str] = ..., api_version: Optional[str] = None, - timezone: Optional[str] = None) -> None: + timezone: Optional[str] = None) -> Optional[int]: """Update the given fields; password is re-encrypted only when provided (non-empty). folder_id: a folder uuid to move the cluster, None to unfile it, omitted to leave it. - timezone: an IANA name to override what the cluster reports, '' to follow the cluster again.""" + timezone: an IANA name to override what the cluster reports, '' to follow the cluster again. + Returns the number of rows changed (0: no such registered cluster), None when nothing was asked.""" sets, params = [], [] if timezone is not None: tz = timezone.strip() @@ -287,8 +308,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,13 +322,20 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: if api_version not in API_VERSIONS: raise ValueError("api_version must be auto, v1 or v2") sets.append('api_version = %s'); params.append(api_version) + if (host is not None or username is not None) and not password: + # the stored password follows the entry: pointed at another address (or user) it would be sent there by + # the next connection test and by every service's next login. Whoever moves it supplies the password. + current = get(cluster_id) + if current and ((host is not None and normalize_host(host) != current.host) + or (username is not None and username.strip() != current.username)): + raise ValueError('changing the address or the user name needs the password in the same request') if not sets: return sets.append('updated_at = NOW()') @@ -314,11 +346,15 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = conn = _connect() try: with conn.cursor() as cur: + # a removed cluster is not changed (enabling one, with no password left, made every service try an + # empty-password login each poll) cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} ' - f'WHERE cluster_id = %s AND is_template = FALSE', params) + f'WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE', params) + changed = cur.rowcount conn.commit() finally: conn.close() + return changed def delete(cluster_id: str, purge: bool = False) -> None: @@ -335,20 +371,26 @@ def delete(cluster_id: str, purge: bool = False) -> None: cur.execute('DELETE FROM config.module_toggles WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.branding WHERE cluster_id = %s', (cluster_id,)) if purge: + # children before the rows they reference: webhook deliveries and the action log point at + # recommendation events, resize advice at right-sizing rows + events = 'SELECT id FROM audit.recommendation_events WHERE cluster_id = %s' + for table in ('audit.webhook_deliveries', 'audit.action_log'): + cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s OR recommendation_event_id IN ({events})', + (cluster_id, cluster_id)) for table in ('recommendations.resize_recommendations', 'recommendations.right_sizing', 'recommendations.forecast_snapshots', 'recommendations.resource_exhaustion', - 'recommendations.cluster_health_scores', 'audit.recommendation_events', - 'audit.action_log', 'audit.webhook_deliveries'): + 'recommendations.cluster_health_scores', 'audit.recommendation_events'): cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.clusters WHERE cluster_id = %s AND is_template = FALSE', (cluster_id,)) else: - # keep the row so FK-bound history stays valid, but take it out of service + # keep the row so FK-bound history stays valid, but take it out of service (once: removing it + # again would append a second '(removed ...)') cur.execute('''UPDATE config.clusters SET enabled = FALSE, is_active = FALSE, hc_password_enc = NULL, cluster_name = cluster_name || ' (removed ' || to_char(NOW(), 'YYYY-MM-DD HH24:MI') || ')', updated_at = NOW() - WHERE cluster_id = %s AND is_template = FALSE''', (cluster_id,)) + WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE''', (cluster_id,)) conn.commit() finally: conn.close() @@ -413,15 +455,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +579,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +589,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +599,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +639,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +719,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +738,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +758,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +785,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +795,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- @@ -836,7 +890,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -851,7 +905,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/backup/constraints.txt b/backup/constraints.txt new file mode 100644 index 0000000..e2b01de --- /dev/null +++ b/backup/constraints.txt @@ -0,0 +1,28 @@ +# Every package of the working backup image, transitive ones included (pip freeze, 2026-11-22, release 1.8.1). +# requirements.txt says what the service needs; this file keeps a rebuild months from now on the +# versions it was tested with (the Dockerfile installs with -c). Regenerate after changing requirements: +# docker run --rm --entrypoint pip freeze +APScheduler==3.11.0 +blinker==1.9.0 +certifi==2026.10.23 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.1 +cryptography==42.0.8 +Flask==3.1.3 +idna==3.20 +itsdangerous==2.2.0 +Jinja2==3.1.6 +MarkupSafe==3.0.4 +psycopg2-binary==2.9.13 +pycparser==3.12 +pyspnego==0.12.4 +python-dateutil==2.9.0.post0 +python-json-logger==4.1.0 +requests==2.34.2 +six==1.17.0 +smbprotocol==1.15.0 +tzdata==2025.2 +tzlocal==5.4.5 +urllib3==2.8.0 +Werkzeug==3.1.9 diff --git a/backup/db.py b/backup/db.py index a9a0454..2f7a6e0 100644 --- a/backup/db.py +++ b/backup/db.py @@ -170,15 +170,17 @@ def delete_schedule(schedule_id: int) -> None: _exec('DELETE FROM backup.plans WHERE id = %s', (schedule_id,)) -def get_known_smb_locations() -> list[dict]: - """Distinct SMB destinations (base + user) saved on schedules, across all clusters, so - an import can reuse them (cross-cluster restore) without re-entering credentials. +def get_known_smb_locations(cluster_ids: list[str]) -> list[dict]: + """Distinct SMB destinations (base + user) saved on the schedules of these clusters (the + importing cluster's folder), so an import can reuse them without re-entering credentials. ref_id is the newest schedule holding the stored password for that location.""" + if not cluster_ids: + return [] return _all( '''SELECT path_uri_base, smb_user, MAX(id) AS ref_id FROM backup.plans - WHERE path_uri_base ILIKE 'smb://%%' AND smb_user IS NOT NULL - GROUP BY path_uri_base, smb_user ORDER BY path_uri_base''') + WHERE path_uri_base ILIKE 'smb://%%' AND smb_user IS NOT NULL AND cluster_id::text = ANY(%s) + GROUP BY path_uri_base, smb_user ORDER BY path_uri_base''', (list(cluster_ids),)) # ----------------------------------------------------------------------- runs @@ -214,6 +216,12 @@ def get_runs(cluster_id: Optional[str] = None, schedule_id: Optional[int] = None return _all(sql, params) +def export_paths(schedule_id: int) -> list[str]: + """Every export folder (tenant/folder) this plan's runs recorded.""" + return [r['export_path'] for r in _all('SELECT DISTINCT export_path FROM backup.runs WHERE schedule_id = %s AND export_path IS NOT NULL', + (schedule_id,))] + + def get_run(run_id: int) -> Optional[dict]: return _one('SELECT * FROM backup.runs WHERE id = %s', (run_id,)) @@ -257,6 +265,19 @@ def folder_name(folder_id: str) -> Optional[str]: return r['name'] if r else None +def folder_backup_dir(folder_id: str, new_dir: str) -> Optional[str]: + """The folder's directory on its target (migration 055). A folder without one gets new_dir, stored + once (COALESCE: a parallel first use keeps whichever was written first). None = no such folder.""" + r = _one('SELECT backup_dir FROM config.folders WHERE folder_id = %s', (folder_id,)) + if r is None: + return None + if r['backup_dir']: + return r['backup_dir'] + r = _one('UPDATE config.folders SET backup_dir = COALESCE(backup_dir, %s) WHERE folder_id = %s RETURNING backup_dir', + (new_dir, folder_id)) + return r['backup_dir'] if r else None + + def _policy_row(r): if r is None: return None @@ -720,6 +741,37 @@ def retire_chains_of_plan(plan_id: int) -> int: return _exec("UPDATE backup.chains SET status = 'retired', plan_id = NULL, updated_at = NOW() WHERE plan_id = %s AND status = 'active'", (plan_id,)) +def empty_chains(cluster_id: str, older_than: datetime) -> list[dict]: + """Chains of a cluster without a single point (also no pruned one), created before older_than, not deleted + and not in use by a running run: the partial data of a failed full that could not be removed at the time.""" + return [_chain_row(r) for r in _all( + """SELECT ch.* FROM backup.chains ch + WHERE ch.cluster_id = %s AND ch.status <> 'deleted' AND ch.created_at < %s + AND NOT EXISTS (SELECT 1 FROM backup.points pt WHERE pt.chain_id = ch.id) + AND NOT EXISTS (SELECT 1 FROM backup.runs r WHERE r.chain_id = ch.id AND r.status = 'RUNNING') + AND NOT EXISTS (SELECT 1 FROM backup.runs r WHERE r.schedule_id = ch.plan_id AND r.status = 'RUNNING')""", + (cluster_id, older_than))] + + +def chain_folders(cluster_id: str) -> list[dict]: + """Every (target, tenant directory) that holds chains of this cluster: where restore directories are made.""" + return _all("""SELECT DISTINCT target_id, folder_slug FROM backup.chains + WHERE cluster_id = %s AND target_id IS NOT NULL AND status <> 'deleted'""", (cluster_id,)) + + +def chains_on_target(target_id: int) -> int: + """Chains (not deleted) whose data lives on this target.""" + r = _one("SELECT COUNT(*) AS n FROM backup.chains WHERE target_id = %s AND status <> 'deleted'", (target_id,)) + return int(r['n']) if r else 0 + + +def chain_work(chain_id: int) -> dict: + """Running backups and restores that use this chain: {'runs': n, 'restores': n}.""" + return _one("""SELECT (SELECT COUNT(*) FROM backup.runs WHERE chain_id = %s AND status = 'RUNNING') AS runs, + (SELECT COUNT(*) FROM backup.restores WHERE chain_id = %s AND status = 'RUNNING') AS restores""", + (chain_id, chain_id)) or {'runs': 0, 'restores': 0} + + def chains_with_clones() -> list[dict]: return [_chain_row(r) for r in _all("SELECT * FROM backup.chains WHERE active_clones IS NOT NULL AND active_clones <> 'null'::jsonb AND jsonb_array_length(active_clones) > 0")] @@ -809,8 +861,8 @@ def get_restores(cluster_id: Optional[str] = None, limit: int = 50) -> list[dict def update_restore(restore_id: int, **fields) -> None: - allowed = {'status', 'message', 'created_uuid', 'finished_at', 'progress'} - items = [(k, _json(v) if k == 'progress' else v) for k, v in fields.items() if k in allowed] + allowed = {'status', 'message', 'created_uuid', 'finished_at', 'progress', 'staging'} + items = [(k, _json(v) if k in ('progress', 'staging') else v) for k, v in fields.items() if k in allowed] if not items: return _exec(f'UPDATE backup.restores SET {", ".join(f"{k} = %s" for k, _ in items)} WHERE id = %s', [v for _, v in items] + [restore_id]) @@ -820,6 +872,13 @@ def get_active_restores() -> list[dict]: return _all("SELECT * FROM backup.restores WHERE status = 'RUNNING' ORDER BY id") +def restores_with_staging() -> list[dict]: + """Finished or failed restores whose staging disks are still recorded (migration 056).""" + return [dict(r, cluster_id=str(r['cluster_id'])) for r in _all( + """SELECT * FROM backup.restores WHERE status <> 'RUNNING' AND staging IS NOT NULL AND jsonb_typeof(staging) = 'array' + AND jsonb_array_length(staging) > 0 ORDER BY id""")] + + # ---------------------------------------------------------------- deployments def add_deployment(cluster_id: str, name: str, params: dict, requested_by: str | None = None) -> int: return _one('INSERT INTO backup.deployments (cluster_id, name, params, requested_by) VALUES (%s,%s,%s,%s) RETURNING id', diff --git a/backup/flr.py b/backup/flr.py index f6b63d6..349afd9 100644 --- a/backup/flr.py +++ b/backup/flr.py @@ -75,6 +75,11 @@ def stream(mount_id: str, kind: str, params: dict): """(requests.Response streaming) for file or zip downloads.""" import requests m, pc = client_for_mount(mount_id) + if pc.url.startswith('https://'): + # the same transport rules as every other proxy call: verify=False below relies on the pin check + if not pc.fingerprint and not pc.tls_verify: + raise ProxyError('https proxy without a pinned certificate fingerprint or CA verification; probe it first') + pc._check_pin() headers = {'Authorization': f'Bearer {pc.token}'} if pc.token else {} verify = pc.tls_verify if pc.url.startswith('https://') and not pc.fingerprint else (False if pc.fingerprint else True) try: diff --git a/backup/hypercore_session.py b/backup/hypercore_session.py index dc09ac0..3ef752f 100644 --- a/backup/hypercore_session.py +++ b/backup/hypercore_session.py @@ -26,12 +26,16 @@ from typing import Callable, Optional import requests +from urllib3.exceptions import ConnectTimeoutError, NewConnectionError import cluster_registry log = logging.getLogger('hypercore_session') TRANSPORT_ERRORS = (requests.exceptions.ConnectionError, requests.exceptions.Timeout) # SSLError is a ConnectionError +# methods HyperCore may receive twice without harm; anything else (a POST that starts a migration, a clone, a new VM) +# is re-sent only when the first attempt provably never reached the node +SAFE_TO_RESEND = frozenset({'GET', 'HEAD', 'OPTIONS'}) class ClusterUnreachable(requests.exceptions.ConnectionError): @@ -76,6 +80,7 @@ def __init__(self, cluster_id: Optional[str], username: str, password: str, veri self.session.verify = self.verify self.host: Optional[str] = self._pinned self.logged_in_at = 0.0 + self.generation = 0 # +1 per successful login: lets a thread see that another one already logged in again self.lock = threading.RLock() if not self.verify: import urllib3 @@ -134,6 +139,7 @@ def login(self, exclude: Optional[str] = None) -> str: attempts.append((h, f'HTTP {r.status_code}')) continue self.host, self.logged_in_at = h, time.monotonic() + self.generation += 1 if attempts: self._log(f'{self.service}: node(s) not answering: ' + '; '.join(f'{a}: {e}' for a, e in attempts)) if previous and previous != h: @@ -177,28 +183,47 @@ def close(self) -> None: def request(self, method: str, path: str, **kw) -> requests.Response: """One REST call on the node in use. A 401 means the session expired: log in again on the same node and retry once. A transport failure means the node is gone: log in on - another candidate and retry once there. Raises ClusterUnreachable / AuthFailed.""" + another candidate and retry once there. Raises ClusterUnreachable / AuthFailed. + + Only GET/HEAD/OPTIONS are re-sent after any transport failure. Other methods are re-sent + only when the request never left (connection refused, connect timeout); a read timeout or + a dropped connection after sending may mean HyperCore accepted it, so that error goes to + the caller instead of a second (or third) migration, clone or VM.""" kw.setdefault('timeout', self.timeout) + resend_any = method.upper() in SAFE_TO_RESEND self.ensure() - host = self.host + host, generation = self.host, self.generation try: try: resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + raise # a pooled keep-alive connection the node already closed ("Remote end closed connection # without response") is no dead node: once more on the same node, on a fresh connection self._log(f'{self.service}: {host} dropped the connection ({_short(e)}); retrying there once') resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + self._log(f'{self.service}: {method} {path} on {host} failed after sending ({_short(e)}); not re-sent') + raise self._log(f'{self.service}: {host} not answering ({_short(e)}); trying another node') with self.lock: - self.logged_in_at = 0.0 - self.login(exclude=host) + if self.generation == generation: # else another thread already moved to a working node + self.logged_in_at = 0.0 + self.login(exclude=host) + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) if resp.status_code == 401: with self.lock: - self.logout() - self.login() + # six threads seeing the same expiry make one new login, and no thread logs out the session + # another thread has just made + if self.generation == generation: + self.logout() + self.login() + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) return resp @@ -214,6 +239,17 @@ def get_json(self, path: str, **kw): return resp.json() +def _not_sent(e: BaseException) -> bool: + """True when the request provably never reached the node: the TCP connection could not be made + (refused, unreachable, DNS) or timed out while connecting.""" + if isinstance(e, requests.exceptions.ConnectTimeout): + return True + if isinstance(e, requests.exceptions.ConnectionError) and e.args: + reason = getattr(e.args[0], 'reason', e.args[0]) + return isinstance(reason, (NewConnectionError, ConnectTimeoutError)) + return False + + def _short(e: BaseException) -> str: s = str(e) if isinstance(e, requests.exceptions.SSLError): diff --git a/backup/incremental.py b/backup/incremental.py index 8f2b1ef..b3e4f2b 100644 --- a/backup/incremental.py +++ b/backup/incremental.py @@ -417,7 +417,8 @@ def plan_point(chain: dict | None, plan: dict, prev_point: dict | None, full: st if not chain.get('anchor_snapshot_uuid'): return 'full', 0, None, 'reference snapshot missing: taking a full instead of an incremental' if plan.get('force_full'): - return 'full', 0, None, 'the last synthetic full could not be built: taking a real full' + return 'full', 0, None, ('a real full was asked for: the last synthetic full could not be built, or the chain ' + 'could not be continued') if full == 'real': return 'full', 0, None, 'full day of the backup schedule' if full is None and int(chain.get('runs_since_full') or 0) >= max(1, int(plan.get('full_every_n') or 14)): @@ -425,6 +426,13 @@ def plan_point(chain: dict | None, plan: dict, prev_point: dict | None, full: st return 'delta', int(chain['next_seq']), int(prev_point['seq']), None +def chain_out_of_step(e: Exception) -> bool: + """The proxy refused a point because the chain on the target is not where the catalogue thinks it is: the + point exists already (the proxy finished one that was never recorded) or its predecessor is missing.""" + text = str(e) + return ' already exists in ' in text or ('previous point ' in text and ' not in chain' in text) + + # ------------------------------------------------------------------ the run def run_incremental(plan_id: int, policy_id: int | None = None, occurrence=None, full: str | None = None) -> None: plan = db.get_schedule(plan_id) @@ -529,6 +537,10 @@ def _run(plan: dict, run_id: int, hc: HyperCoreClient | None = None, work_starte db.update_chain(chain['id'], anchor_snapshot_uuid=None) chain['anchor_snapshot_uuid'] = None kind, seq, prev_seq, note = plan_point(chain, plan, prev_point, full) + if kind == 'delta' and chain.get('target_id') != share['id']: + # the folder got another target: the chain's points live on its own target, a delta on the new one has no + # base. The old chain retires there and expires through retention on that target. + kind, seq, prev_seq, note = 'full', 0, None, "the folder's backup target changed: taking a full on the new target" if kind == 'full' and chain is not None: # a new full starts a new chain; the old one retires and expires through retention db.update_chain(chain['id'], status='retired') @@ -563,69 +575,89 @@ def _run(plan: dict, run_id: int, hc: HyperCoreClient | None = None, work_starte make_way(proxy['id'], 'a backup') lock.acquire() lock_wait = time.monotonic() - wait_t0 + # the proxy lock is released exactly once, in the finally, whatever is raised in between (a requests error the + # proxy client does not wrap, a database error); the new anchor goes when the run did not get through + unchanged, failed = False, True try: - # 2. clones + 3. maps - req_devices = [] - for dev in devices: - cap = device_capacity(dev) - clone_uuid = clone_onto(hc, dev['uuid'], snap_uuid, proxy['vm_uuid'], cap, read_only=True) - clones.append(clone_uuid) - db.update_chain(chain['id'], active_clones=clones) - serial = serials.get(dev['uuid']) - if dev['type'] in HyperCoreClient.DISK_TYPES: - if kind == 'delta' and dev['uuid'] in prev_serials and dev['uuid'] not in resized: - dev_map = hc.snap_diff(dev['uuid'], prev_serials[dev['uuid']], serial) - entry = {'map': dev_map} + try: + # 2. clones + 3. maps + req_devices = [] + for dev in devices: + cap = device_capacity(dev) + clone_uuid = clone_onto(hc, dev['uuid'], snap_uuid, proxy['vm_uuid'], cap, read_only=True) + clones.append(clone_uuid) + db.update_chain(chain['id'], active_clones=clones) + serial = serials.get(dev['uuid']) + if dev['type'] in HyperCoreClient.DISK_TYPES: + if kind == 'delta' and dev['uuid'] in prev_serials and dev['uuid'] not in resized: + dev_map = hc.snap_diff(dev['uuid'], prev_serials[dev['uuid']], serial) + entry = {'map': dev_map} + else: + entry = {'map': hc.snap_diff(dev['uuid'], 0, serial)} + if kind == 'delta': + # new or resized disk inside a delta point: the proxy writes it without a + # backing file (`full`); `full_map` is what older proxies read + entry['full_map'] = entry['map'] + entry['full'] = True else: - entry = {'map': hc.snap_diff(dev['uuid'], 0, serial)} - if kind == 'delta': - # new or resized disk inside a delta point: the proxy writes it without a - # backing file (`full`); `full_map` is what older proxies read - entry['full_map'] = entry['map'] - entry['full'] = True - else: - entry = {'map': [{'lower': 0, 'upper': 0}]} # NVRAM / vTPM: 1 MiB, always re-copied - req_devices.append({'uuid': dev['uuid'], 'type': dev['type'], 'clone_uuid': clone_uuid, 'size': cap, - 'image_size': image_size(dev), 'serial': serial, **entry}) - blocks = sum(jobs_blocks(d['map']) for d in req_devices) - disk_blocks = sum(jobs_blocks(d['map']) for d in req_devices if d['type'] in HyperCoreClient.DISK_TYPES) - if kind == 'delta' and disk_blocks == 0: - # nothing changed on any disk since the previous point: no new point, keep the old anchor - db.update_chain(chain['id'], active_clones=_delete_clones(hc, clones)) - lock.release() - _safe_delete_snapshot(hc, snap_uuid, 'unneeded anchor') - end = _now() - db.update_run(run_id, status='COMPLETE', finished_at=end, blocks_changed=0, bytes_written=0, - message='No blocks changed since the previous point; nothing written.', - **jobs.run_timing(work_started, lock_wait, 0.0, end)) - log.info('[run %s] no changes, skipped', run_id) - return - db.update_run(run_id, blocks_changed=blocks, message=f'{kind}: {blocks} MiB to copy, proxy {proxy["name"]}') - - # 4. proxy job - body = {'target': {'uri': share['uri_base'], 'username': share.get('username'), 'password': share.get('password')}, - 'folder': loc['tenant'], 'vm': {'uuid': vm['uuid'], 'name': vm['name']}, 'chain_dir': chain['chain_dir'], - 'point': {'kind': kind, 'seq': seq, 'previous_seq': prev_seq}, 'devices': req_devices, - 'definition': definition, 'plan_id': plan['id'], 'run_id': run_id} - job_id = pc.submit('backup', body) - - def on_progress(p): - if p.get('blocks_total'): - total_dev = p.get('devices_total', 1) - try: # progress text is cosmetic: a db hiccup must not abort the copy - db.update_run(run_id, message=backup_progress_text(kind, p), progress=backup_progress(p)) - except Exception as e: # noqa: BLE001 - log.warning('[run %s] progress update failed: %s', run_id, e) - result = pc.wait(job_id, on_progress, timeout=CFG.task_timeout_hours * 3600)['result'] - except Exception: - db.update_chain(chain['id'], active_clones=_delete_clones(hc, clones)) + entry = {'map': [{'lower': 0, 'upper': 0}]} # NVRAM / vTPM: 1 MiB, always re-copied + req_devices.append({'uuid': dev['uuid'], 'type': dev['type'], 'clone_uuid': clone_uuid, 'size': cap, + 'image_size': image_size(dev), 'serial': serial, **entry}) + blocks = sum(jobs_blocks(d['map']) for d in req_devices) + disk_blocks = sum(jobs_blocks(d['map']) for d in req_devices if d['type'] in HyperCoreClient.DISK_TYPES) + # nothing changed on any disk since the previous point: no proxy job, no new point (see below) + unchanged = kind == 'delta' and disk_blocks == 0 + if not unchanged: + db.update_run(run_id, blocks_changed=blocks, message=f'{kind}: {blocks} MiB to copy, proxy {proxy["name"]}') + + # 4. proxy job + body = {'target': {'uri': share['uri_base'], 'username': share.get('username'), 'password': share.get('password')}, + 'folder': loc['tenant'], 'vm': {'uuid': vm['uuid'], 'name': vm['name']}, 'chain_dir': chain['chain_dir'], + 'point': {'kind': kind, 'seq': seq, 'previous_seq': prev_seq}, 'devices': req_devices, + 'definition': definition, 'plan_id': plan['id'], 'run_id': run_id} + job_id = pc.submit('backup', body) + + def on_progress(p): + if p.get('blocks_total'): + total_dev = p.get('devices_total', 1) + try: # progress text is cosmetic: a db hiccup must not abort the copy + db.update_run(run_id, message=backup_progress_text(kind, p), progress=backup_progress(p)) + except Exception as e: # noqa: BLE001 + log.warning('[run %s] progress update failed: %s', run_id, e) + try: + result = pc.wait(job_id, on_progress, timeout=CFG.task_timeout_hours * 3600)['result'] + except ProxyError as e: + if not chain_out_of_step(e): + raise + # the target holds a point this catalogue never recorded (a restart or a database error after + # the proxy finished): this chain cannot be continued, the next run starts a new one + db.update_schedule(plan['id'], force_full=True) + raise ProxyError(f'{e}; the next run starts a new chain with a full') from e + leftover = _delete_clones(hc, clones) + failed = False + except Exception: + try: + db.update_chain(chain['id'], active_clones=_delete_clones(hc, clones)) + except Exception: # noqa: BLE001 — the run's own error is what matters + log.warning('[run %s] clones of the failed run not recorded for the sweep', run_id, exc_info=True) + raise + finally: lock.release() - _safe_delete_snapshot(hc, snap_uuid, 'new anchor') - raise + if failed: + _safe_delete_snapshot(hc, snap_uuid, 'new anchor') + + if unchanged: + # no new point, keep the old anchor + _safe_delete_snapshot(hc, snap_uuid, 'unneeded anchor') + db.update_chain(chain['id'], active_clones=leftover) + end = _now() + db.update_run(run_id, status='COMPLETE', finished_at=end, blocks_changed=0, bytes_written=0, + message='No blocks changed since the previous point; nothing written.', + **jobs.run_timing(work_started, lock_wait, 0.0, end)) + log.info('[run %s] no changes, skipped', run_id) + return # 5. bookkeeping - leftover = _delete_clones(hc, clones) - lock.release() point_id = db.add_point(chain['id'], seq, kind, result['point_dir'], serials, blocks, result.get('bytes_written', 0), result.get('duration_s', 0), result.get('devices', []), definition, run_id, quiesced=quiesced) db.update_chain(chain['id'], anchor_snapshot_uuid=snap_uuid, last_serials=serials, next_seq=seq + 1, @@ -754,11 +786,19 @@ def apply_retention(plan: dict, pc: ProxyClient, share: dict) -> str: by_chain: dict[int, list[dict]] = {} for p in drop: by_chain.setdefault(p['chain_id'], []).append(p) - pruned = 0 + pruned, skipped = 0, 0 for chain_id, pts in by_chain.items(): chain = db.get_chain(chain_id) + # every chain is pruned on its own target: after a target change the old chains are still on the old one + # (deleting them on the new target "succeeds" on a missing directory and the data would stay for ever) + cshare = share if chain.get('target_id') == share['id'] else ( + db.get_share(chain['target_id'], with_secret=True) if chain.get('target_id') else None) + if not cshare: + log.warning('retention: chain %s has no target any more; its points are left alone', chain_id) + skipped += len(pts) + continue remaining = [p for p in db.get_points(chain_id) if p['id'] not in {x['id'] for x in pts}] - body = {'target': {'uri': share['uri_base'], 'username': share.get('username'), 'password': share.get('password')}, + body = {'target': {'uri': cshare['uri_base'], 'username': cshare.get('username'), 'password': cshare.get('password')}, 'chain_dir': chain['chain_dir']} try: if not remaining: @@ -779,7 +819,8 @@ def apply_retention(plan: dict, pc: ProxyClient, share: dict) -> str: pruned += len(pts) except ProxyError as e: return f'Retention: pruning failed on chain {chain_id}: {e}' - return f'Retention: pruned {pruned} point(s), {len(points) - pruned} kept.' + return (f'Retention: pruned {pruned} point(s), {len(points) - pruned} kept' + + (f' ({skipped} due on a chain whose target no longer exists)' if skipped else '') + '.') # ------------------------------------------------------------------ sweeps @@ -808,6 +849,10 @@ def sweep_cluster(cluster_id: str, max_age_days: int = 30) -> dict: _delete_clones(hc, list(ch.get('active_clones') or [])) db.update_chain(ch['id'], active_clones=[]) out['clones'] += len(ch.get('active_clones') or []) + try: + out.update(sweep_targets(cluster_id)) + except Exception: # noqa: BLE001 — e.g. no proxy reachable: tomorrow again + log.warning('sweep of targets for cluster %s failed', cluster_id, exc_info=True) for p in db.get_proxies(cluster_id): if not p.get('vm_uuid'): continue @@ -820,6 +865,48 @@ def sweep_cluster(cluster_id: str, max_age_days: int = 30) -> dict: return out +def sweep_targets(cluster_id: str, now: datetime | None = None) -> dict: + """On the targets, through one of the cluster's proxies: chains without any point older than a day (a failed + full whose partial data discard_empty_chain could not remove), each on its own target, and restore + directories (/_restore/*) older than a day that a failed restore left behind.""" + out = {'empty_chains': 0, 'restore_dirs': 0} + from datetime import timedelta + cutoff = (now or _now()) - timedelta(days=1) + empty = db.empty_chains(cluster_id, cutoff) + folders = db.chain_folders(cluster_id) + if not empty and not folders: + return out + pc = proxy_client_for(pick_proxy(cluster_id)) + shares: dict = {} + + def target(tid): + if tid not in shares: + s = db.get_share(tid, with_secret=True) if tid else None + shares[tid] = {'uri': s['uri_base'], 'username': s.get('username'), 'password': s.get('password')} if s else None + return shares[tid] + for ch in empty: + t = target(ch.get('target_id')) + try: + if t: + pc.wait(pc.submit('delete_chain', {'target': t, 'chain_dir': ch['chain_dir']}), timeout=3600) + db.update_chain(ch['id'], status='deleted') + release_anchor(ch) + out['empty_chains'] += 1 + log.info('sweep: chain %s without points removed (%s)', ch['id'], ch['chain_dir']) + except ProxyError as e: + log.warning('sweep: chain %s without points not removed: %s', ch['id'], e) + for f in folders: + t = target(f['target_id']) + if not t or jobs.is_nfs(t['uri']): # restores (and so restore directories) are SMB only + continue + try: + res = pc.wait(pc.submit('sweep', {'target': t, 'folder': f['folder_slug'], 'older_than_hours': 24}), timeout=600) + out['restore_dirs'] += len((res.get('result') or {}).get('removed') or []) + except ProxyError as e: + log.warning('sweep: restore directories in %s not removed: %s', f['folder_slug'], e) + return out + + def remove_cloud_init_disk(hc: HyperCoreClient, vm_uuid: str) -> str | None: """HyperCore keeps the cloud-init document of a deployed proxy VM as a NoCloud ISO attached to the VM, on a Scribe volume anyone with access to the VM can clone or mount; the document @@ -891,6 +978,9 @@ def verify_chain(chain: dict, share: dict, pc: ProxyClient, upto_seq: int | None if upto_seq is not None: body['upto_seq'] = int(upto_seq) res = pc.wait(pc.submit('verify', body), on_progress=on_progress, timeout=timeout)['result'] or {} + if res.get('healed'): + # a prune by a proxy before 0.6.3 left stale checksums in these points; 0.6.5 re-took them once + log.info('chain %s: checksums re-taken after a prune by an older proxy: %s', chain['id'], ', '.join(res['healed'])) ok, failed = record_verify_result(chain['id'], res) res['ok'] = ok res['failed'] = failed diff --git a/backup/jobs.py b/backup/jobs.py index 63c2be7..3fdbfa8 100644 --- a/backup/jobs.py +++ b/backup/jobs.py @@ -69,11 +69,23 @@ def build_path_uri(base: str, user: str | None, password: str | None) -> str: def tenant_slug(cluster) -> str: - """Share subfolder for a cluster: its HyperCore Manager folder name made filesystem-safe - (spaces and other awkward characters become underscores). Clusters without a folder share - one `no_folder` subfolder.""" + """Share subfolder for a cluster: the directory stored on its HyperCore Manager folder + (config.folders.backup_dir, migration 055). Folders that existed before 055 keep their old + name-derived directory; a newer folder gets `-` on first use, + because folder names are unique per parent only and two tenants' "Production" folders must not + share one directory. A rename never moves it. Clusters without a folder share one `no_folder` + subfolder.""" name = getattr(cluster, 'folder_name', None) if cluster is not None else None - return safe_name(name) if name else 'no_folder' + legacy = safe_name(name) if name else 'no_folder' + folder_id = getattr(cluster, 'folder_id', None) if cluster is not None else None + if not folder_id: + return legacy + try: + stored = db.folder_backup_dir(str(folder_id), f'{legacy}-{str(folder_id)[:8]}') + except Exception as e: # noqa: BLE001 -- database before migration 055: the old directory + log.warning('backup directory of folder %s not readable, using its name: %s', folder_id, e) + return legacy + return stored or legacy def location_for_cluster(cluster_id: str) -> dict | None: @@ -102,7 +114,7 @@ def location_for_schedule(sched) -> dict: if loc: return loc if not sched.get('path_uri_base'): - raise HyperCoreError("no share assigned to this cluster's folder (Settings → Shares, then the folder menu)") + raise HyperCoreError("no backup target is assigned to this cluster's folder (Settings → Targets, then Backup target in the folder's menu in the cluster switcher)") cluster = cluster_registry.get(sched['cluster_id']) tenant = tenant_slug(cluster) return { @@ -115,6 +127,17 @@ def location_for_schedule(sched) -> dict: } +def under_location(uri: str | None, base: str | None) -> bool: + """True when uri is base itself or lies inside it (no `..` segment): the only URIs a folder target's + stored credentials may be put into.""" + if not uri or not base: + return False + uri, base = uri.rstrip('/').lower(), base.rstrip('/').lower() + if '..' in urlsplit(uri).path.split('/'): + return False + return uri == base or uri.startswith(base + '/') + + def effective_base(sched) -> str: """Kept for the API: the resolved / path, or '' when unresolvable.""" try: @@ -142,8 +165,8 @@ def client_for(cluster_id: str) -> HyperCoreClient: def derive_name(folder: str) -> str: - """Strip a `_YYYYMMDD-HHMMSS` export suffix to guess the original VM name.""" - m = re.match(r'^(.*)_\d{8}-\d{6}$', folder or '') + """Strip a `[_uuid8]_YYYYMMDD-HHMMSS` export suffix to guess the original VM name.""" + m = re.match(r'^(.*?)(?:_[0-9a-f]{8})?_\d{8}-\d{6}$', folder or '') return m.group(1) if m else (folder or '') @@ -353,7 +376,7 @@ def run_export(schedule_id: int, policy_id: int | None = None, occurrence=None) run_id = db.start_run(schedule_id, policy_id, occurrence) db.update_run(run_id, mode='export') - folder = f"{safe_name(sched['vm_name'])}_{datetime.now().strftime(TIMESTAMP_FMT)}" + folder = export_folder(sched['vm_name'], sched.get('vm_uuid'), datetime.now().strftime(TIMESTAMP_FMT)) try: loc = location_for_schedule(sched) except HyperCoreError as e: @@ -479,17 +502,42 @@ def smb_list_dirs(base_uri: str, user: str, password: str | None) -> list[str]: return sorted(names, reverse=True) -def select_excess(dir_names, vm_name: str, retention: int): - """Which folders to delete: only this VM's `{safe_name}_YYYYMMDD-HHMMSS` folders are - candidates, sibling VMs are never touched; the newest `retention` are kept.""" - prefix = safe_name(vm_name) + '_' - pattern = re.compile(re.escape(prefix) + r'\d{8}-\d{6}$') - copies = sorted(n for n in dir_names if pattern.match(n)) +def export_folder(vm_name: str, vm_uuid: str | None, stamp: str) -> str: + """`{safe_name}_{first 8 of the VM uuid}_YYYYMMDD-HHMMSS`: the tenant directory is shared by every cluster of + the folder, so the name alone would let two clusters' VMs called "dc01" prune each other's exports.""" + short = re.sub(r'[^0-9A-Za-z]', '', vm_uuid or '')[:8] + return f'{safe_name(vm_name)}_{short}_{stamp}' if short else f'{safe_name(vm_name)}_{stamp}' + + +def select_excess(dir_names, vm_name: str, retention: int, vm_uuid: str | None = None, own_legacy=()): + """Which folders to delete: only this VM's `{safe_name}_{uuid8}_YYYYMMDD-HHMMSS` folders are candidates, + sibling VMs (also a namesake on another cluster of the folder) are never touched; the newest `retention` + are kept. A folder in the older `{safe_name}_YYYYMMDD-HHMMSS` form counts only when it is in + `own_legacy` (recorded in this plan's own runs). Without vm_uuid: the old name-only rule.""" + stamp = r'\d{8}-\d{6}$' + if vm_uuid: + pattern = re.compile(re.escape(export_folder(vm_name, vm_uuid, '')) + stamp) + legacy = re.compile(re.escape(safe_name(vm_name) + '_') + stamp) + own = set(own_legacy or ()) + copies = [n for n in dir_names if pattern.match(n) or (n in own and legacy.match(n))] + copies.sort(key=lambda n: n[-15:]) # by timestamp: legacy and new names interleave + else: + pattern = re.compile(re.escape(safe_name(vm_name) + '_') + stamp) + copies = sorted(n for n in dir_names if pattern.match(n)) excess = copies[:-retention] if retention > 0 else [] kept = min(len(copies), retention) return excess, kept +def _own_legacy(sched) -> set: + """Export folder names recorded in this plan's runs (to recognise its exports from before the uuid suffix).""" + try: + return {p.rsplit('/', 1)[-1] for p in db.export_paths(sched['id'])} + except Exception as e: # noqa: BLE001 -- no history: legacy folders are simply kept + log.warning('export history of plan %s not readable: %s', sched.get('id'), e) + return set() + + def prune_old_exports(sched) -> str: """Delete the oldest export folders beyond the retention count. SMB locations are pruned over the protocol with the share's credentials; NFS through the share's mount path.""" @@ -511,7 +559,7 @@ def _prune_via_mount(sched, loc) -> str: if not base.is_dir(): return f'Pruning skipped: {base} is not accessible from this container.' names = [d.name for d in base.iterdir() if d.is_dir()] - excess, kept = select_excess(names, sched['vm_name'], sched['retention']) + excess, kept = select_excess(names, sched['vm_name'], sched['retention'], sched.get('vm_uuid'), _own_legacy(sched)) for name in excess: try: shutil.rmtree(base / name) @@ -533,7 +581,7 @@ def _prune_via_smb(sched, loc) -> str: names = [e.name for e in smbclient.scandir(unc_base, **conn) if e.is_dir()] except Exception as e: # noqa: BLE001 return f'Pruning skipped: could not list {unc_base} over SMB: {e}' - excess, kept = select_excess(names, sched['vm_name'], sched['retention']) + excess, kept = select_excess(names, sched['vm_name'], sched['retention'], sched.get('vm_uuid'), _own_legacy(sched)) for name in excess: try: smb_shutil.rmtree(unc_base + '\\' + name, **conn) @@ -558,8 +606,13 @@ def run_import(import_id: int) -> None: password = db.decrypt_password(imp['smb_pass_enc']) if imp['smb_pass_enc'] else None source_uri = build_path_uri(imp['source_uri'], imp['smb_user'], password) else: + # the folder target's credentials go only into a URI inside that folder's own directory, never into + # a source somebody typed elsewhere loc = location_for_cluster(imp['cluster_id']) - source_uri = build_path_uri(imp['source_uri'], loc['user'] or None, loc['password'] or None) if loc else imp['source_uri'] + if loc and under_location(imp['source_uri'], loc['base']): + source_uri = build_path_uri(imp['source_uri'], loc['user'] or None, loc['password'] or None) + else: + source_uri = imp['source_uri'] task_tag, created = hc.import_vm(source_uri, name=imp['target_name'] or None) db.update_import(import_id, task_tag=task_tag, created_uuid=created or None) wait_for_task(hc, task_tag, lambda state, pct: db.update_import(import_id, message=f'{state} {pct}%')) diff --git a/backup/proxy_client.py b/backup/proxy_client.py index c2f0965..0fa7ac0 100644 --- a/backup/proxy_client.py +++ b/backup/proxy_client.py @@ -146,13 +146,34 @@ def job(self, job_id: str) -> dict: def cancel(self, job_id: str) -> None: self._request('DELETE', f'/jobs/{job_id}') - def wait(self, job_id: str, on_progress=None, timeout: float = 8 * 3600, poll: float = 3) -> dict: + def _cancel_quietly(self, job_id: str) -> None: + try: + self.cancel(job_id) + except ProxyError: + pass + + def wait(self, job_id: str, on_progress=None, timeout: float = 8 * 3600, poll: float = 3, outage: float = 300) -> dict: """Poll until the job finishes. on_progress(progress_dict) when progress changes. - Returns the job; raises ProxyError when it failed or was cancelled.""" + Returns the job; raises ProxyError when it failed or was cancelled. The proxy may be unreachable + for up to `outage` seconds in a row (a network blip must not throw away a multi-hour full); after + that, or at the timeout, the job is cancelled (best effort) and ProxyError raised.""" deadline = time.monotonic() + timeout last = None + down_since = None while time.monotonic() < deadline: - j = self.job(job_id) + try: + j = self.job(job_id) + except ProxyError as e: + if e.kind != 'unreachable': + raise + now = time.monotonic() + down_since = down_since if down_since is not None else now + if now - down_since >= outage: + self._cancel_quietly(job_id) + raise ProxyError(f'{e} (unreachable for {outage / 60:.0f} minutes; job cancelled)', kind='unreachable') from e + time.sleep(poll) + continue + down_since = None p = j.get('progress') or {} if on_progress and p != last: on_progress(p) @@ -162,10 +183,7 @@ def wait(self, job_id: str, on_progress=None, timeout: float = 8 * 3600, poll: f if j['state'] in ('failed', 'cancelled'): raise ProxyError(j.get('error') or f'proxy job {job_id} {j["state"]}') time.sleep(poll) - try: - self.cancel(job_id) - finally: - pass + self._cancel_quietly(job_id) raise ProxyError(f'proxy job {job_id} did not finish within {timeout / 3600:.1f}h') diff --git a/backup/proxy_image.py b/backup/proxy_image.py index 6c5c4dd..61fd002 100644 --- a/backup/proxy_image.py +++ b/backup/proxy_image.py @@ -21,6 +21,7 @@ import config as cfg_module import db +import incremental from proxy_client import ProxyClient, ProxyError log = logging.getLogger('backup.proxy_image') @@ -93,6 +94,11 @@ def push(client: ProxyClient, source: Callable[[], tuple[str, Iterable[bytes]]] return answer +# A backup or restore holds incremental.proxy_lock from its first clone until its proxy job is done: the proxy can +# look idle (no job yet) while clones are being attached, and a container restart in that moment breaks the run. +BUSY = 'a job is running on this proxy (or a backup or restore is preparing one); retry when it is idle' + + def prepare(proxy_id: int, *, force: bool = False, client_factory=None, info=stack_image) -> dict: """The checks before a push, quick enough for an API call: the proxy exists and is remote, the installation has an amd64 image, the proxy answers, is behind (or force), has the hook @@ -119,8 +125,8 @@ def prepare(proxy_id: int, *, force: bool = False, client_factory=None, info=sta return {'skipped': 'already on this version', 'version': current} if not (ident.get('capabilities') or {}).get('update'): raise ProxyError(f"proxy runs {current}, the installation {stack['version']}; it has no update hook, update its container by hand") - if client.active_jobs(): - raise ProxyError('a job is running on this proxy; retry when it is idle') + if client.active_jobs() or incremental.proxy_lock(proxy_id).locked(): + raise ProxyError(BUSY) return {'proxy': p, 'client': client, 'current': current, 'stack': stack} @@ -132,6 +138,16 @@ def update_proxy(proxy_id: int, *, force: bool = False, client_factory=None, sou pre = prepare(proxy_id, force=force, client_factory=client_factory, info=info) if pre.get('skipped'): return {'ok': True, **pre} + lock = incremental.proxy_lock(proxy_id) + if not lock.acquire(blocking=False): # no waiting: the update pass skips a busy proxy + raise ProxyError(BUSY) + try: + return _push_and_wait(proxy_id, pre, source, sleep, wait_seconds) + finally: + lock.release() + + +def _push_and_wait(proxy_id: int, pre: dict, source, sleep, wait_seconds: float) -> dict: client, current, stack = pre['client'], pre['current'], pre['stack'] db.update_proxy(proxy_id, status='updating', status_detail=f"updating {current} -> {stack['version']}") push_error = None diff --git a/backup/restore.py b/backup/restore.py index f429ef8..a56559b 100644 --- a/backup/restore.py +++ b/backup/restore.py @@ -93,13 +93,94 @@ def run_restore(restore_id: int) -> None: try: _run(r) except (IncrementalError, HyperCoreError, ProxyError, ValueError, vm_definition.UnknownMachineType) as e: - db.update_restore(restore_id, status='ERROR', message=str(e), finished_at=_now(), progress=None) + db.update_restore(restore_id, status='ERROR', message=str(e) + _discard_failed_vm(restore_id), finished_at=_now(), progress=None) log.error('[restore %s] %s', restore_id, e) except Exception as e: # noqa: BLE001 - db.update_restore(restore_id, status='ERROR', message=f'Unexpected error: {e}', finished_at=_now(), progress=None) + db.update_restore(restore_id, status='ERROR', message=f'Unexpected error: {e}' + _discard_failed_vm(restore_id), + finished_at=_now(), progress=None) log.exception('[restore %s] unexpected error', restore_id) +def _record_staging(rid: int, uuids: list[str]) -> None: + """Staging disks on the proxy VM that this restore still owns (migration 056); never fails the restore.""" + try: + db.update_restore(rid, staging=list(uuids)) + except Exception as e: # noqa: BLE001 — e.g. before migration 056 + log.warning('[restore %s] staging disks not recorded: %s', rid, e) + + +def remove_staging(hc: HyperCoreClient, uuids: list[str]) -> list[str]: + """Delete staging disks still attached to a proxy VM; a disk that is gone already counts as removed. + Returns the ones that could not be removed.""" + present = [] + for u in uuids or []: + try: + if hc.get_block_device(u): + present.append(u) + except HyperCoreError as e: + if e.status != 404: + present.append(u) + return _delete_clones(hc, present) if present else [] + + +def _discard_failed_vm(rid: int, require_unfinished: bool = False) -> str: + """Delete the VM a failed restore created (half-built, it also blocks a retry with the same name). Only the + VM recorded on this restore, and only while it is off. With require_unfinished, only when the restore had + not reached its last step (an interrupted restore). Returns a note for the message ('' = nothing done).""" + try: + r = db.get_restore(rid) or {} + vm_uuid = r.get('created_uuid') + if not vm_uuid or (r.get('kind') or 'vm') != 'vm' or (require_unfinished and (r.get('progress') or {}).get('phase') == 'finish'): + return '' + hc = jobs.client_for(r['cluster_id']) + try: + vm = hc.get_vm(vm_uuid) + except HyperCoreError: + return '' # gone already + if (vm.get('state') or '').upper() not in ('SHUTOFF', 'SHUTDOWN'): + return f"; the restored VM '{vm.get('name')}' is running and was kept" + t = hc.delete_vm(vm_uuid) + if t: + wait_task(hc, t, 'delete the half-restored VM', 600) + log.warning('[restore %s] half-restored VM %s deleted', rid, vm_uuid) + return '; the half-restored VM was deleted' + except Exception as e: # noqa: BLE001 — the restore's own error is what matters + log.warning('[restore %s] half-restored VM not deleted: %s', rid, e) + return f'; the half-restored VM could not be deleted ({e}), delete it on the cluster' + + +def cleanup_interrupted(restore_ids: list[int]) -> None: + """After a restart: the staging disks and the half-built VM of restores the restart interrupted.""" + for rid in restore_ids: + note = _discard_failed_vm(rid, require_unfinished=True) + if note: + try: + r = db.get_restore(rid) or {} + db.update_restore(rid, message=(r.get('message') or 'Interrupted by a restart.') + note) + except Exception: # noqa: BLE001 + log.warning('[restore %s] note not recorded', rid, exc_info=True) + sweep_staging() + + +def sweep_staging() -> int: + """Daily and after a restart: staging disks that finished or failed restores left on proxy VMs.""" + removed = 0 + try: + rows = db.restores_with_staging() + except Exception: # noqa: BLE001 — before migration 056 + log.debug('staging sweep skipped', exc_info=True) + return 0 + for r in rows: + try: + left = remove_staging(jobs.client_for(r['cluster_id']), list(r['staging'])) + except HyperCoreError as e: + log.warning('[restore %s] staging disks not removed yet: %s', r['id'], e) + continue + removed += len(r['staging']) - len(left) + _record_staging(r['id'], left) + return removed + + def _run(r: dict) -> None: rid = r['id']; params = r.get('params') or {} point = db.get_point(r['point_id']) @@ -167,6 +248,8 @@ def _run(r: dict) -> None: tags = ','.join(t for t in [*(definition.get('tags') or '').split(','), *(params.get('extra_tags') or [])] if t.strip()) tag, created = hc.import_vm(source_uri, name=name, description=params.get('description') or definition.get('description') or '', tags=tags, definition_file=f'{dirname}.xml') + if created: + db.update_restore(rid, created_uuid=created) # known before the import finishes: a failure removes it wait_task(hc, tag, 'import', 3600) new_vm = hc.get_vm(created) if created else next((v for v in hc.list_vms_full() if (v.get('name') or '').lower() == name.lower()), None) if not new_vm: @@ -184,8 +267,9 @@ def _run(r: dict) -> None: cap = int(d['capacity']) # staging disks take heavy one-off writes: keep them off the SSD tier (factor 0) stag, su = jobs.retry_transient(lambda: hc.create_block_device(proxy['vm_uuid'], cap, tiering=0), 'create staging disk') - wait_task(hc, stag, 'create staging disk', 600) staging.append((d, su)) + _record_staging(rid, [s for _, s in staging]) # a restart or a failed cleanup must not lose them + wait_task(hc, stag, 'create staging disk', 600) db.update_restore(rid, message=f'writing {len(disks)} disk(s) to the proxy', progress={'phase': 'write', 'done': 0, 'total': 0}) res = pc.wait(pc.submit('stage', {'target': target, 'chain_dir': chain['chain_dir'], 'seq': point['seq'], 'devices': [{'uuid': d['uuid'], 'staging_clone_uuid': su} for d, su in staging]}), @@ -208,6 +292,8 @@ def _run(r: dict) -> None: # the clone inherits the staging disk's tiering (0) whatever the template says: put the # source's factor back, or the restored VM runs from an uncached disk fields = {'tieringPriorityFactor': tiering} + if d.get('cacheMode'): + fields['cacheMode'] = d['cacheMode'] # recorded in the point; the clone gets HyperCore's default if d.get('name'): fields['name'] = d['name'] # an orchestrator's identity for the volume (CSI) t = jobs.retry_transient(lambda: hc.patch_block_device(new_dev, **fields), 'disk settings') @@ -215,9 +301,11 @@ def _run(r: dict) -> None: wait_task(hc, t, 'disk settings', 300) finally: _safe_delete_snapshot(hc, snap_uuid, 'restore staging') - _delete_clones(hc, [su for _, su in staging]) + if staging: + _record_staging(rid, _delete_clones(hc, [su for _, su in staging])) # the daily sweep retries what is left # 5. boot order, NICs, start + db.update_restore(rid, message='boot order and network', progress={'phase': 'finish'}) new_vm = hc.get_vm(new_vm['uuid']) order = boot_order(definition, disk_map, new_vm) if order: @@ -228,6 +316,9 @@ def _run(r: dict) -> None: connected = bool(params.get('nic_connected', not source_exists)) for new_nic, old_nic in zip(new_vm.get('netDevs', []), definition.get('netDevs', [])): fields = {'connected': connected} + if old_nic.get('type') and old_nic['type'] != new_nic.get('type'): + # the restore template always renders a virtio NIC: an E1000 or RTL8139 guest would come back without network + fields['type'] = old_nic['type'] if params.get('vlan') is not None: fields['vlan'] = int(params['vlan']) # a test restore on the network level: the isolated test VLAN elif old_nic.get('vlan') is not None: @@ -249,7 +340,9 @@ def _run(r: dict) -> None: not_started = str(e) log.warning('[restore %s] restored VM not started: %s', rid, e) try: - pc.wait(pc.submit('sweep', {'target': target, 'folder': chain['folder_slug'], 'older_than_hours': 0}), timeout=600) + # only this restore's own directory: a sweep of /_restore could delete a parallel restore's import + # directory; older leftovers go with the daily sweep (incremental.sweep_targets) + pc.wait(pc.submit('delete_chain', {'target': target, 'chain_dir': out_dir}), timeout=600) except ProxyError as e: log.warning('[restore %s] restore directory cleanup failed: %s', rid, e) bytes_written = res.get('bytes_written', 0) diff --git a/backup/scheduler.py b/backup/scheduler.py index 82f4958..0ef3290 100644 --- a/backup/scheduler.py +++ b/backup/scheduler.py @@ -6,6 +6,8 @@ import os import threading +from apscheduler.events import EVENT_JOB_MISSED +from apscheduler.executors.pool import ThreadPoolExecutor from apscheduler.schedulers.background import BackgroundScheduler import db @@ -14,11 +16,52 @@ log = logging.getLogger('backup.scheduler') -_scheduler = BackgroundScheduler(job_defaults={ - 'max_instances': 1, # never run the same schedule twice at once - 'coalesce': True, # collapse missed runs into one - 'misfire_grace_time': 3600, -}) +# Work that takes minutes to hours (backups, exports, restores, imports, deployments) runs on its own, larger +# pool: on the shared 10-thread pool a busy night left one-off jobs waiting for a thread, and a job that waited +# longer than its grace time was dropped without a trace (a restore stayed RUNNING, a policy run blocked its +# plan for good). The minute ticks keep the default pool, so they never wait behind a long job. +LONG_WORKERS = 64 +_scheduler = BackgroundScheduler( + executors={'default': ThreadPoolExecutor(10), 'long': ThreadPoolExecutor(LONG_WORKERS)}, + job_defaults={ + 'max_instances': 1, # never run the same schedule twice at once + 'coalesce': True, # collapse missed runs into one + 'misfire_grace_time': 3600, + }) + + +def _one_off(func, args: list, job_id: str) -> None: + """A job asked for now (run now, restore, import, policy run, ...): on the long pool, and never dropped for + starting late (misfire_grace_time None: however long it waited for a thread).""" + _scheduler.add_job(func, args=args, id=job_id, replace_existing=True, executor='long', misfire_grace_time=None) + + +def _on_missed(event) -> None: + """A job APScheduler skipped (it started too late). Nothing else would ever close its row or its slot.""" + jid = str(event.job_id or '') + head, _, num = jid.rpartition('-') + if not num.isdigit(): + return + n = int(num) + msg = 'did not start: the backup service was too busy; start it again' + log.error('job %s was missed (started too late) and skipped', jid) + try: + if head == 'policy-run': + with _policy_runs_lock: + _policy_runs.pop(n, None) + elif head in ('restore', 'iso'): + db.update_restore(n, status='ERROR', finished_at=db.now_utc(), message=f'Restore {msg}.') + elif head in ('import', 'resume-import'): + db.update_import(n, status='ERROR', finished_at=db.now_utc(), message=f'Import {msg}.') + elif head == 'deploy': + db.update_deployment(n, status='ERROR', finished_at=db.now_utc(), message=f'Deployment {msg}.') + elif head == 'resume-run': + db.update_run(n, status='ERROR', finished_at=db.now_utc(), message=f'Resume after a restart {msg}.') + except Exception: # noqa: BLE001 — a listener must never raise into APScheduler + log.exception('could not record the missed job %s', jid) + + +_scheduler.add_listener(_on_missed, EVENT_JOB_MISSED) def _job_id(schedule_id: int) -> str: @@ -40,7 +83,7 @@ def sync_jobs() -> int: for job_id, s in wanted.items(): hour, minute = s['run_time'].split(':') _scheduler.add_job(jobs.run_plan, trigger='cron', hour=int(hour), minute=int(minute), timezone=plan_timezone(s), - id=job_id, args=[s['id']], replace_existing=True) + id=job_id, args=[s['id']], replace_existing=True, executor='long') return len(wanted) @@ -81,8 +124,7 @@ def dispatch(plan_id, policy_id, occurrence, cluster_id, kind, full=None, manual with _policy_runs_lock: _policy_runs[plan_id] = (cluster_id, kind) try: - _scheduler.add_job(_policy_run, args=[plan_id, policy_id, occurrence, full, manual], id=f'policy-run-{plan_id}', - replace_existing=True) + _one_off(_policy_run, [plan_id, policy_id, occurrence, full, manual], f'policy-run-{plan_id}') except Exception: with _policy_runs_lock: _policy_runs.pop(plan_id, None) @@ -96,27 +138,27 @@ def dispatch(plan_id, policy_id, occurrence, cluster_id, kind, full=None, manual def run_now(schedule_id: int) -> None: - _scheduler.add_job(jobs.run_plan, args=[schedule_id], id=f'manual-{schedule_id}', replace_existing=True) + _one_off(jobs.run_plan, [schedule_id], f'manual-{schedule_id}') def run_restore(restore_id: int) -> None: import restore - _scheduler.add_job(restore.run_restore, args=[restore_id], id=f'restore-{restore_id}', replace_existing=True) + _one_off(restore.run_restore, [restore_id], f'restore-{restore_id}') def run_iso_delivery(restore_id: int) -> None: import flr - _scheduler.add_job(flr.deliver_iso, args=[restore_id], id=f'iso-{restore_id}', replace_existing=True) + _one_off(flr.deliver_iso, [restore_id], f'iso-{restore_id}') def run_deployment(dep_id: int) -> None: import deploy - _scheduler.add_job(deploy.run_deployment, args=[dep_id], id=f'deploy-{dep_id}', replace_existing=True) + _one_off(deploy.run_deployment, [dep_id], f'deploy-{dep_id}') def run_proxy_update(proxy_id: int) -> None: import proxy_image - _scheduler.add_job(proxy_image.update_proxy, args=[proxy_id], id=f'proxy-update-{proxy_id}', replace_existing=True) + _one_off(proxy_image.update_proxy, [proxy_id], f'proxy-update-{proxy_id}') def update_proxies() -> None: @@ -129,7 +171,7 @@ def update_proxies() -> None: def run_import(import_id: int) -> None: - _scheduler.add_job(jobs.run_import, args=[import_id], id=f'import-{import_id}', replace_existing=True) + _one_off(jobs.run_import, [import_id], f'import-{import_id}') def reconcile_interrupted() -> None: @@ -138,12 +180,19 @@ def reconcile_interrupted() -> None: for r in db.get_active_runs(): if r.get('mode') == 'incremental': # the proxy job may still be running, but its result is lost to us: fail the run, the - # sweep removes clones and the next run re-anchors (a full if the anchor is gone) + # sweep removes clones. A delta that reached the copy may exist on the target without being + # recorded; continuing would submit the same point again and the proxy refuses it every night, + # so that plan starts a new chain with a full (a lost full leaves a chain without points, which + # the next run replaces anyway) + copied = r.get('point_kind') == 'delta' and r.get('blocks_changed') is not None + if copied: + db.update_schedule(r['schedule_id'], force_full=True) db.update_run(r['id'], status='ERROR', finished_at=db.now_utc(), - message='Interrupted by a restart; the next run continues the chain.') + message='Interrupted by a restart; the next run ' + + ('starts a new chain with a full.' if copied else 'continues the chain.')) continue if r['task_tag']: - _scheduler.add_job(jobs.resume_export, args=[r['id']], id=f"resume-run-{r['id']}", replace_existing=True) + _one_off(jobs.resume_export, [r['id']], f"resume-run-{r['id']}") log.info('Resuming interrupted export run %s (task %s)', r['id'], r['task_tag']) else: db.update_run(r['id'], status='ERROR', finished_at=db.now_utc(), @@ -151,11 +200,17 @@ def reconcile_interrupted() -> None: for x in db.get_deployments(): if x['status'] == 'RUNNING': db.update_deployment(x['id'], status='ERROR', finished_at=db.now_utc(), message='Interrupted by a restart; check the VM on the cluster and register the proxy by hand if it is up.') + interrupted = [] for x in db.get_active_restores(): db.update_restore(x['id'], status='ERROR', finished_at=db.now_utc(), message='Interrupted by a restart.') + interrupted.append(x['id']) + if interrupted: + # their staging disks on the proxy VM and the half-built VM go, off the start path (HyperCore calls) + import restore + _one_off(restore.cleanup_interrupted, [interrupted], 'restore-cleanup') for i in db.get_active_imports(): if i['task_tag']: - _scheduler.add_job(jobs.resume_import, args=[i['id']], id=f"resume-import-{i['id']}", replace_existing=True) + _one_off(jobs.resume_import, [i['id']], f"resume-import-{i['id']}") log.info('Resuming interrupted import %s (task %s)', i['id'], i['task_tag']) else: db.update_import(i['id'], status='ERROR', finished_at=db.now_utc(), @@ -173,6 +228,13 @@ def sweep_all() -> None: log.info('sweep %s: %s', c.name, out) except Exception: # noqa: BLE001 log.exception('sweep failed for %s', c.name) + try: + import restore + n = restore.sweep_staging() + if n: + log.info('restore staging disks left on proxy VMs: %s removed', n) + except Exception: # noqa: BLE001 + log.exception('restore staging sweep failed') try: db.prune_nights(90) except Exception: # noqa: BLE001 @@ -258,7 +320,7 @@ def _verify_reconcile() -> None: def enqueue_vm_change(change_id: int) -> None: - _scheduler.add_job(vmedit.run, args=[change_id], id=f'vmedit-{change_id}', replace_existing=True) + _one_off(vmedit.run, [change_id], f'vmedit-{change_id}') def _vm_changes_reconcile() -> None: @@ -289,7 +351,7 @@ def start(sync_interval_seconds: int = 60) -> None: next_run_time=_dt.now() + _td(seconds=20)) _scheduler.add_job(sync_jobs, trigger='interval', seconds=sync_interval_seconds, id='sync', replace_existing=True) _scheduler.add_job(policy_tick, trigger='cron', second=5, id='policy-tick', replace_existing=True) - _scheduler.add_job(sweep_all, trigger='cron', hour=4, minute=30, id='sweep', replace_existing=True) + _scheduler.add_job(sweep_all, trigger='cron', hour=4, minute=30, id='sweep', replace_existing=True, executor='long') # planned verification (per folder, point by point); replaces the Sunday 05:00 re-read of every chain _scheduler.add_job(_verify_reconcile, trigger='date', run_date=_dt.now() + _td(seconds=10), id='verify-reconcile', replace_existing=True) @@ -306,21 +368,67 @@ def start(sync_interval_seconds: int = 60) -> None: next_run_time=_dt.now() + _td(seconds=900)) # first sweep a little after start: the dashboard applies new migrations at the same moment from datetime import datetime, timedelta - _scheduler.add_job(sweep_all, trigger='date', run_date=datetime.now() + timedelta(seconds=120), id='sweep-start', replace_existing=True) + _scheduler.add_job(sweep_all, trigger='date', run_date=datetime.now() + timedelta(seconds=120), id='sweep-start', replace_existing=True, executor='long') # proxies follow the stack's version: one pass shortly after every (re)start, when the dashboard is up again - _scheduler.add_job(update_proxies, trigger='date', run_date=datetime.now() + timedelta(seconds=180), id='proxy-update-start', replace_existing=True) + _scheduler.add_job(update_proxies, trigger='date', run_date=datetime.now() + timedelta(seconds=180), id='proxy-update-start', replace_existing=True, executor='long') # on an upgrade the dashboard may still be applying the migrations this code reads: log and let # the periodic sync (and a delayed reconcile) catch up instead of taking the service down try: n = sync_jobs() - reconcile_interrupted() + _after_start() log.info('Scheduler started with %d active schedule(s)', n) except Exception: # noqa: BLE001 log.exception('Scheduler start: database not ready, retrying with the periodic sync') - _scheduler.add_job(reconcile_interrupted, trigger='date', run_date=datetime.now() + timedelta(seconds=90), + _scheduler.add_job(_after_start, trigger='date', run_date=datetime.now() + timedelta(seconds=90), id='reconcile-start', replace_existing=True) +def _after_start() -> None: + reconcile_interrupted() + catch_up() + + +# Standalone plans live in APScheduler's memory job store: a run time that passed while the service was down +# (a stack update at night) was simply skipped until the next day. One missed within this window runs at start. +CATCH_UP_HOURS = 4 + + +def missed_fire(run_time: str, tz: str, now): + """The plan's last daily run time before `now` (aware), when it lies within CATCH_UP_HOURS; else None.""" + from datetime import timedelta as _td + from zoneinfo import ZoneInfo + local = now.astimezone(ZoneInfo(tz)) + hh, mm = (int(x) for x in run_time.split(':')) + fire = local.replace(hour=hh, minute=mm, second=0, microsecond=0) + if fire > local: + fire -= _td(days=1) + return fire if local - fire <= _td(hours=CATCH_UP_HOURS) else None + + +def catch_up(now=None) -> list[int]: + """Start every standalone plan whose run time passed in the last CATCH_UP_HOURS without a run since.""" + from datetime import datetime as _dt, timezone as _tz + now = now or _dt.now(_tz.utc) + started = [] + for s in db.get_schedules(): + if not s['enabled'] or not s.get('cluster_enabled', True) or s.get('policy_id'): + continue # policy members: the dispatcher works from its windows + try: + fire = missed_fire(s['run_time'], plan_timezone(s), now) + except (ValueError, AttributeError): + continue + if fire is None: + continue + last = db.last_run_for(s['id']) + if last and last.get('started_at') and last['started_at'] >= fire: + continue + log.warning('plan %s (%s) missed its run at %s while the service was down: running it now', s['id'], s['vm_name'], + fire.isoformat(timespec='minutes')) + run_now(s['id']) + started.append(s['id']) + return started + + def next_run_time(schedule_id: int): job = _scheduler.get_job(_job_id(schedule_id)) return job.next_run_time if job else None diff --git a/backup/vmedit.py b/backup/vmedit.py index 1f5b096..6990fb5 100644 --- a/backup/vmedit.py +++ b/backup/vmedit.py @@ -20,7 +20,7 @@ import re import threading import time -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Any, Optional import psycopg2.extras @@ -181,6 +181,9 @@ def plan(kind: str, ops: list[dict], vm: dict, ctx: Optional[dict] = None) -> di summary += [_describe_vm_field(k, v) for k, v in fields.items()] elif op == 'disk_resize': d = _dev(vm, o.get('device'), 'disk') + if d.get('type') not in DISK_TYPES: + # HyperCore answers a resize of the NVRAM, vTPM or a CD-ROM with a 500 (live: four retries, then failed) + raise EditError(f"only a disk can grow, not the {d.get('type') or 'unknown'} device") cap = _int(o.get('capacity'), 'disk size', 1, 64 * 1024 * GIB) if cap <= int(d.get('capacity') or 0): raise EditError(f"disk {d.get('name') or d.get('type')} can only grow") @@ -497,6 +500,8 @@ def _state(hc, vm_uuid: str) -> str: SHUTDOWN_REPEAT = 60 +LATE_SHUTDOWN_WATCH = 30 * 60 # after the user's timeout: how long a late guest shutdown is still caught +MISSED_WINDOW = timedelta(minutes=30) # a scheduled set that could not start this long after its time is not run def _wait_off(hc, vm_uuid: str, seconds: float, repeat=None) -> bool: @@ -529,9 +534,16 @@ def _power_off(hc, ch: dict, step: _Step) -> None: step('OS shutdown', True, 'the VM is off') return if not ch['force_off']: - step('OS shutdown', False, f'the guest did not shut down within {mins} min') - raise EditError(f'the guest did not shut down within {mins} minutes; nothing was changed and the VM keeps ' - 'running (tick "force power off" to power it off in that case)') + # the guest has the shutdown request and may still act on it: a VM that went off later stayed off, as nobody + # started it again. Keep watching; if it goes off now, the set carries on (apply, start) as if in time. + late = LATE_SHUTDOWN_WATCH // 60 + step('OS shutdown', False, f'the guest did not shut down within {mins} min; watching {late} min more') + if _wait_off(hc, vm, LATE_SHUTDOWN_WATCH): + step('OS shutdown', True, f'the VM went off after the {mins} min timeout') + return + raise EditError(f'the guest did not shut down within {mins} minutes (nor {late} minutes after that); nothing was ' + 'changed. The guest got the shutdown request: if it still shuts down later, the VM stays off; check ' + 'it (tick "force power off" to power it off at the timeout instead)') step('OS shutdown', False, f'the guest did not shut down within {mins} min: powering off') jobs.retry_transient(lambda: hc.vm_action(vm, 'STOP'), 'power off') if not _wait_off(hc, vm, 300): @@ -603,6 +615,14 @@ def run(change_id: int) -> None: vm_uuid = ch['vm_uuid'] was_running = False off_by_us = False + run_at = ch.get('run_at') + if run_at and datetime.now(timezone.utc) - run_at > MISSED_WINDOW: + # the service was down at its time: a Sunday 02:00 maintenance set must not run on Monday morning + step('start', False, f'due at {run_at.isoformat(timespec="minutes")}') + _finish(change_id, 'failed', result, f'missed its window: it was due at {run_at.isoformat(timespec="minutes")} and could not ' + f'start within {int(MISSED_WINDOW.total_seconds() // 60)} minutes; nothing was done, ' + 'schedule it again') + return try: hc = jobs.client_for(ch['cluster_id']) pf = jobs.preflight(hc, ch['cluster_id']) diff --git a/console/Dockerfile b/console/Dockerfile index e75c436..893a5f3 100644 --- a/console/Dockerfile +++ b/console/Dockerfile @@ -1,12 +1,15 @@ -FROM python:3.12-slim +# the Debian release is named: package names (apt) differ between releases, and a rebuild must not +# move to the next one unasked +FROM python:3.12-slim-trixie # tesseract reads login prompts and lock-screen texts for the open console session check RUN apt-get update && apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-eng \ && rm -rf /var/lib/apt/lists/* WORKDIR /app -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY requirements.txt constraints.txt ./ +# constraints.txt: every transitive package at the version this release was tested with +RUN pip install --no-cache-dir -r requirements.txt -c constraints.txt COPY . . RUN useradd -r -u 997 hcmconsole diff --git a/console/checker.py b/console/checker.py index 7f3980e..ca9cb4a 100644 --- a/console/checker.py +++ b/console/checker.py @@ -57,6 +57,14 @@ async def check_vm(http: aiohttp.ClientSession, cluster_id: str, vm_uuid: str, s if verdict.state == 'open': log.info('console session open', extra={'cluster_id': cluster_id, 'vm': name, 'vm_uuid': vm_uuid}) return {'state': verdict.state, 'detail': verdict.detail} + except Exception as e: # noqa: BLE001 — without a verdict the VM stays most overdue and takes a slot every tick + detail = consoles.mask_session(f'check failed: {type(e).__name__}: {e}')[:300] + log.warning('open-session check of %s failed: %s', vm_uuid, detail, extra={'cluster_id': cluster_id}) + try: + await asyncio.to_thread(store.record_verdict, cluster_id, vm_uuid, None, 'error', detail) + except Exception: # noqa: BLE001 — database down: the next round tries again + log.warning('verdict for %s not recorded', vm_uuid, exc_info=True) + return {'state': 'error', 'detail': detail} finally: _busy.discard(key) diff --git a/console/cluster_registry.py b/console/cluster_registry.py index 2157c49..8650f82 100644 --- a/console/cluster_registry.py +++ b/console/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -162,9 +177,11 @@ def _row_to_cluster(r: dict) -> Cluster: # --------------------------------------------------------------------------- def list_all(include_template: bool = False) -> list[Cluster]: - sql = f'SELECT {_COLUMNS} {_FROM}' + """The registered clusters. A removed one (Remove keeps its row, renamed '(removed ...)', so history stays + valid) is not registered any more and is left out: it showed up with an Enable button.""" + sql = f'SELECT {_COLUMNS} {_FROM} WHERE c.is_active = TRUE' if not include_template: - sql += ' WHERE c.is_template = FALSE' + sql += ' AND c.is_template = FALSE' sql += ' ORDER BY c.is_template DESC, lower(c.cluster_name)' conn = _connect() try: @@ -238,7 +255,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -270,10 +290,11 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = username: Optional[str] = None, password: Optional[str] = None, verify_tls: Optional[bool] = None, colour: Optional[str] = None, enabled: Optional[bool] = None, folder_id: Optional[str] = ..., api_version: Optional[str] = None, - timezone: Optional[str] = None) -> None: + timezone: Optional[str] = None) -> Optional[int]: """Update the given fields; password is re-encrypted only when provided (non-empty). folder_id: a folder uuid to move the cluster, None to unfile it, omitted to leave it. - timezone: an IANA name to override what the cluster reports, '' to follow the cluster again.""" + timezone: an IANA name to override what the cluster reports, '' to follow the cluster again. + Returns the number of rows changed (0: no such registered cluster), None when nothing was asked.""" sets, params = [], [] if timezone is not None: tz = timezone.strip() @@ -287,8 +308,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,13 +322,20 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: if api_version not in API_VERSIONS: raise ValueError("api_version must be auto, v1 or v2") sets.append('api_version = %s'); params.append(api_version) + if (host is not None or username is not None) and not password: + # the stored password follows the entry: pointed at another address (or user) it would be sent there by + # the next connection test and by every service's next login. Whoever moves it supplies the password. + current = get(cluster_id) + if current and ((host is not None and normalize_host(host) != current.host) + or (username is not None and username.strip() != current.username)): + raise ValueError('changing the address or the user name needs the password in the same request') if not sets: return sets.append('updated_at = NOW()') @@ -314,11 +346,15 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = conn = _connect() try: with conn.cursor() as cur: + # a removed cluster is not changed (enabling one, with no password left, made every service try an + # empty-password login each poll) cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} ' - f'WHERE cluster_id = %s AND is_template = FALSE', params) + f'WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE', params) + changed = cur.rowcount conn.commit() finally: conn.close() + return changed def delete(cluster_id: str, purge: bool = False) -> None: @@ -335,20 +371,26 @@ def delete(cluster_id: str, purge: bool = False) -> None: cur.execute('DELETE FROM config.module_toggles WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.branding WHERE cluster_id = %s', (cluster_id,)) if purge: + # children before the rows they reference: webhook deliveries and the action log point at + # recommendation events, resize advice at right-sizing rows + events = 'SELECT id FROM audit.recommendation_events WHERE cluster_id = %s' + for table in ('audit.webhook_deliveries', 'audit.action_log'): + cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s OR recommendation_event_id IN ({events})', + (cluster_id, cluster_id)) for table in ('recommendations.resize_recommendations', 'recommendations.right_sizing', 'recommendations.forecast_snapshots', 'recommendations.resource_exhaustion', - 'recommendations.cluster_health_scores', 'audit.recommendation_events', - 'audit.action_log', 'audit.webhook_deliveries'): + 'recommendations.cluster_health_scores', 'audit.recommendation_events'): cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.clusters WHERE cluster_id = %s AND is_template = FALSE', (cluster_id,)) else: - # keep the row so FK-bound history stays valid, but take it out of service + # keep the row so FK-bound history stays valid, but take it out of service (once: removing it + # again would append a second '(removed ...)') cur.execute('''UPDATE config.clusters SET enabled = FALSE, is_active = FALSE, hc_password_enc = NULL, cluster_name = cluster_name || ' (removed ' || to_char(NOW(), 'YYYY-MM-DD HH24:MI') || ')', updated_at = NOW() - WHERE cluster_id = %s AND is_template = FALSE''', (cluster_id,)) + WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE''', (cluster_id,)) conn.commit() finally: conn.close() @@ -413,15 +455,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +579,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +589,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +599,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +639,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +719,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +738,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +758,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +785,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +795,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- @@ -836,7 +890,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -851,7 +905,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/console/consoles.py b/console/consoles.py index 46757aa..5a8c9da 100644 --- a/console/consoles.py +++ b/console/consoles.py @@ -21,6 +21,7 @@ import hmac import logging import os +import re import secrets import time from dataclasses import dataclass, field @@ -90,6 +91,27 @@ def consume(token: str, binding: str) -> Optional[Ticket]: return t +_SESSION_RE = re.compile(r'(sessionID=)[^&\s\'"]*', re.I) + + +def mask_session(text: str) -> str: + """`text` with any HyperCore sessionID in it masked.""" + return _SESSION_RE.sub(r'\1***', text) + + +def _upstream_failure(e: BaseException) -> str: + """What went wrong connecting to the cluster's console, never its URL: that carries HyperCore's + sessionID, and this text goes to the log, the check details on the dashboard and API errors. + aiohttp's WSServerHandshakeError (a ClientResponseError) renders as status, message and URL.""" + if isinstance(e, aiohttp.ClientResponseError): + return f'the cluster answered HTTP {e.status}' + if isinstance(e, asyncio.TimeoutError): + return 'timed out' + if isinstance(e, OSError): # connect errors: host, port and the OS error + return mask_session(str(e)) + return type(e).__name__ + + async def open_upstream(http: aiohttp.ClientSession, cluster_id: str, vm_uuid: str): """(websocket to HyperCore's console of this VM, target). Raises hc.ConsoleError.""" target = await asyncio.to_thread(hc.console_target, cluster_id, vm_uuid) @@ -98,7 +120,7 @@ async def open_upstream(http: aiohttp.ClientSession, cluster_id: str, vm_uuid: s max_msg_size=0, timeout=aiohttp.ClientWSTimeout(ws_close=5), autoping=True) except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as e: - raise hc.ConsoleError(f'console connection to the cluster failed: {e}', 502) from None + raise hc.ConsoleError(f'console connection to the cluster failed: {_upstream_failure(e)}', 502) from None return ws, target @@ -117,9 +139,15 @@ async def relay(request: web.Request, http: aiohttp.ClientSession) -> web.WebSoc await down.close(code=4502, message=str(e)[:120].encode()) return down - sid = await asyncio.to_thread(store.session_start, ticket.cluster_id, ticket.vm_uuid, target.vm_name, - ticket.username, client_ip=ticket.client_ip, source=ticket.source, - guest_grant_id=ticket.grant_id) + try: + sid = await asyncio.to_thread(store.session_start, ticket.cluster_id, ticket.vm_uuid, target.vm_name, + ticket.username, client_ip=ticket.client_ip, source=ticket.source, + guest_grant_id=ticket.grant_id) + except Exception: # noqa: BLE001 — no audit record, no console; the cluster's websocket must not stay open + log.exception('console session for %s could not be recorded; not opened', ticket.vm_uuid) + await up.close() + await down.close(code=4502, message=b'the console session could not be recorded') + return down started = time.monotonic() state = {'last_input': started, 'in': 0, 'out': 0} max_s = min(MAX_HOURS * 3600, (ticket.max_minutes or 1e9) * 60) @@ -130,6 +158,8 @@ async def relay(request: web.Request, http: aiohttp.ClientSession) -> web.WebSoc 'vm_uuid': ticket.vm_uuid, 'cluster_id': ticket.cluster_id, 'client_ip': ticket.client_ip}) + view_filter = rfb.ViewOnlyFilter() if ticket.view_only else None + async def browser_to_cluster(): async for msg in down: if msg.type == aiohttp.WSMsgType.BINARY: @@ -139,8 +169,10 @@ async def browser_to_cluster(): else: break state['in'] += len(data) - if ticket.view_only and rfb.carries_input(data): - continue # read-only: keys, pointer and clipboard never reach the VM + if view_filter is not None: + data = view_filter.feed(data) # read-only: only screen-update traffic reaches the VM + if not data: + continue if rfb.is_user_input(data, True): state['last_input'] = time.monotonic() await up.send_bytes(data) @@ -173,7 +205,7 @@ async def limits(): try: reason = t.result() or reason except Exception as e: # noqa: BLE001 — a dropped socket mid-send - reason = f'connection error: {e}'[:200] + reason = mask_session(f'connection error: {e}')[:200] finally: for t in tasks: t.cancel() @@ -194,15 +226,16 @@ async def screenshot(http: aiohttp.ClientSession, cluster_id: str, vm_uuid: str, source: str = 'user', wake: str = 'none'): """(PIL image, vm name) of the VM's console right now, audited as a screenshot session.""" up, target = await open_upstream(http, cluster_id, vm_uuid) - sid = await asyncio.to_thread(store.session_start, cluster_id, vm_uuid, target.vm_name, username, - source=source, kind='screenshot') - reason = 'ok' + sid, reason = None, 'ok' try: + sid = await asyncio.to_thread(store.session_start, cluster_id, vm_uuid, target.vm_name, username, + source=source, kind='screenshot') img = await rfb.screenshot(up, wake=wake) return img, target.vm_name except rfb.RFBError as e: reason = f'failed: {e}'[:200] raise hc.ConsoleError(f'screenshot failed: {e}', 502) from None finally: - await up.close() - await asyncio.to_thread(store.session_end, sid, reason) + await up.close() # also when the audit record could not be written + if sid is not None: + await asyncio.to_thread(store.session_end, sid, reason) diff --git a/console/constraints.txt b/console/constraints.txt new file mode 100644 index 0000000..58aba32 --- /dev/null +++ b/console/constraints.txt @@ -0,0 +1,25 @@ +# Every package of the working console image, transitive ones included (pip freeze, 2026-11-22, release 1.8.1). +# requirements.txt says what the service needs; this file keeps a rebuild months from now on the +# versions it was tested with (the Dockerfile installs with -c). Regenerate after changing requirements: +# docker run --rm --entrypoint pip freeze +aiohappyeyeballs==2.7.1 +aiohttp==3.12.15 +aiosignal==1.4.0 +attrs==26.1.0 +certifi==2026.10.23 +cffi==2.1.1 +charset-normalizer==3.5.2 +cryptography==42.0.8 +frozenlist==1.8.0 +idna==3.20 +multidict==6.9.1 +pillow==13.0.0 +propcache==0.5.4 +psycopg2-binary==2.9.13 +pycparser==3.12 +python-json-logger==4.1.0 +requests==2.34.2 +typing_extensions==4.16.0 +tzdata==2025.2 +urllib3==2.8.0 +yarl==1.25.1 diff --git a/console/hypercore_session.py b/console/hypercore_session.py index dc09ac0..3ef752f 100644 --- a/console/hypercore_session.py +++ b/console/hypercore_session.py @@ -26,12 +26,16 @@ from typing import Callable, Optional import requests +from urllib3.exceptions import ConnectTimeoutError, NewConnectionError import cluster_registry log = logging.getLogger('hypercore_session') TRANSPORT_ERRORS = (requests.exceptions.ConnectionError, requests.exceptions.Timeout) # SSLError is a ConnectionError +# methods HyperCore may receive twice without harm; anything else (a POST that starts a migration, a clone, a new VM) +# is re-sent only when the first attempt provably never reached the node +SAFE_TO_RESEND = frozenset({'GET', 'HEAD', 'OPTIONS'}) class ClusterUnreachable(requests.exceptions.ConnectionError): @@ -76,6 +80,7 @@ def __init__(self, cluster_id: Optional[str], username: str, password: str, veri self.session.verify = self.verify self.host: Optional[str] = self._pinned self.logged_in_at = 0.0 + self.generation = 0 # +1 per successful login: lets a thread see that another one already logged in again self.lock = threading.RLock() if not self.verify: import urllib3 @@ -134,6 +139,7 @@ def login(self, exclude: Optional[str] = None) -> str: attempts.append((h, f'HTTP {r.status_code}')) continue self.host, self.logged_in_at = h, time.monotonic() + self.generation += 1 if attempts: self._log(f'{self.service}: node(s) not answering: ' + '; '.join(f'{a}: {e}' for a, e in attempts)) if previous and previous != h: @@ -177,28 +183,47 @@ def close(self) -> None: def request(self, method: str, path: str, **kw) -> requests.Response: """One REST call on the node in use. A 401 means the session expired: log in again on the same node and retry once. A transport failure means the node is gone: log in on - another candidate and retry once there. Raises ClusterUnreachable / AuthFailed.""" + another candidate and retry once there. Raises ClusterUnreachable / AuthFailed. + + Only GET/HEAD/OPTIONS are re-sent after any transport failure. Other methods are re-sent + only when the request never left (connection refused, connect timeout); a read timeout or + a dropped connection after sending may mean HyperCore accepted it, so that error goes to + the caller instead of a second (or third) migration, clone or VM.""" kw.setdefault('timeout', self.timeout) + resend_any = method.upper() in SAFE_TO_RESEND self.ensure() - host = self.host + host, generation = self.host, self.generation try: try: resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + raise # a pooled keep-alive connection the node already closed ("Remote end closed connection # without response") is no dead node: once more on the same node, on a fresh connection self._log(f'{self.service}: {host} dropped the connection ({_short(e)}); retrying there once') resp = self.session.request(method, f'{self.base_url}{path}', **kw) except TRANSPORT_ERRORS as e: + if not (resend_any or _not_sent(e)): + self._log(f'{self.service}: {method} {path} on {host} failed after sending ({_short(e)}); not re-sent') + raise self._log(f'{self.service}: {host} not answering ({_short(e)}); trying another node') with self.lock: - self.logged_in_at = 0.0 - self.login(exclude=host) + if self.generation == generation: # else another thread already moved to a working node + self.logged_in_at = 0.0 + self.login(exclude=host) + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) if resp.status_code == 401: with self.lock: - self.logout() - self.login() + # six threads seeing the same expiry make one new login, and no thread logs out the session + # another thread has just made + if self.generation == generation: + self.logout() + self.login() + elif not self.logged_in_at: + self.login() resp = self.session.request(method, f'{self.base_url}{path}', **kw) return resp @@ -214,6 +239,17 @@ def get_json(self, path: str, **kw): return resp.json() +def _not_sent(e: BaseException) -> bool: + """True when the request provably never reached the node: the TCP connection could not be made + (refused, unreachable, DNS) or timed out while connecting.""" + if isinstance(e, requests.exceptions.ConnectTimeout): + return True + if isinstance(e, requests.exceptions.ConnectionError) and e.args: + reason = getattr(e.args[0], 'reason', e.args[0]) + return isinstance(reason, (NewConnectionError, ConnectTimeoutError)) + return False + + def _short(e: BaseException) -> str: s = str(e) if isinstance(e, requests.exceptions.SSLError): diff --git a/console/rfb.py b/console/rfb.py index f0332ba..c6be8ca 100644 --- a/console/rfb.py +++ b/console/rfb.py @@ -171,25 +171,73 @@ def is_user_input(msg: bytes, handshake_done: bool) -> bool: return i != len(msg) -def carries_input(msg: bytes) -> bool: - """True when a browser -> console message (after the handshake) holds a key event, a pointer event - or clipboard text: what a read-only viewer must not send. Screen-update requests (alone or batched), - the pixel format and the encodings pass; so do the handshake's short messages (version, security - choice, the shared flag), none of which starts with 4, 5 or 6.""" - if not msg: - return False - if msg[0] in (4, 5, 6): - return True - if msg[0] == 3: - i = 0 - while i + _SIZES[3] <= len(msg): - if msg[i] in (4, 5, 6): - return True - if msg[i] != 3: - return False - i += _SIZES[3] - return i < len(msg) and msg[i] in (4, 5, 6) - return False +class ViewOnlyFilter: + """The browser -> console byte stream of a read-only session, parsed as RFB: what reaches the VM is + the client's handshake (version, security choice, shared flag) and then only complete + SetPixelFormat (0), SetEncodings (2) and FramebufferUpdateRequest (3) messages. Key and pointer + events and clipboard text are skipped by their length; any other type (QEMU's extended key event + 255 among them) ends what can be parsed of that websocket message, and the rest of it is dropped. + The server therefore only ever sees whole messages of the three allowed types, whatever the browser + packs into a frame (looking at a frame's first byte let input ride behind an allowed message).""" + _FORWARD = {0: 20, 3: 10} # fixed sizes; 2 is 4 + 4 per encoding + _SKIP = {4: 8, 5: 6} # 6 is 8 + its text length + + def __init__(self): + self.buf = bytearray() + self.stage = 'version' # version | init | messages + self.init_left = 0 + self.skip = 0 + + def feed(self, data: bytes) -> bytes: + """Bytes of one websocket message in, the bytes that may go to the console out.""" + self.buf += data + out = bytearray() + while self.buf: + if self.skip: + n = min(self.skip, len(self.buf)) + del self.buf[:n] + self.skip -= n + continue + if self.stage == 'version': + if len(self.buf) < 12: + break + version = bytes(self.buf[:12]) + del self.buf[:12] + if not version.startswith(b'RFB '): + self.buf.clear() + break + out += version + # 3.3: the server picks the security type, ClientInit follows; 3.7+: security choice, then ClientInit + self.stage, self.init_left = 'init', 1 if version[8:11] < b'007' else 2 + continue + if self.stage == 'init': + out += self.buf[:1] + del self.buf[:1] + self.init_left -= 1 + if not self.init_left: + self.stage = 'messages' + continue + t = self.buf[0] + if t in self._FORWARD or t == 2: + if t == 2: + if len(self.buf) < 4: + break + size = 4 + 4 * struct.unpack_from('>H', self.buf, 2)[0] + else: + size = self._FORWARD[t] + if len(self.buf) < size: + break # the rest comes in the next message + out += self.buf[:size] + del self.buf[:size] + elif t in self._SKIP: + self.skip = self._SKIP[t] + elif t == 6: + if len(self.buf) < 8: + break + self.skip = 8 + abs(struct.unpack_from('>i', self.buf, 4)[0]) # negative: extended clipboard + else: + self.buf.clear() # length unknown: nothing more of this message is passed + return bytes(out) def first_message_type(msg: bytes) -> Optional[int]: diff --git a/dashboard/Dockerfile b/dashboard/Dockerfile index 9c6d048..2225006 100644 --- a/dashboard/Dockerfile +++ b/dashboard/Dockerfile @@ -1,4 +1,6 @@ -FROM python:3.11-slim +# the Debian release is named: package names (apt) differ between releases, and a rebuild must not +# move to the next one unasked +FROM python:3.11-slim-trixie WORKDIR /app # install system dependencies (curl for vendor assets, git + docker compose v2 for auto-update) @@ -14,8 +16,30 @@ RUN apt-get update && apt-get install -y curl git docker.io && rm -rf /var/lib/a docker-compose version && \ git config --global --add safe.directory /repo -COPY dashboard/requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +# External assets for offline/dark-site support. Before the application files, so the layer is cached +# from one release to the next; -f so a CDN error page fails the build instead of shipping as chart.js. +RUN mkdir -p static/vendor && \ + curl -fsSL "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js" -o static/vendor/chart.umd.min.js && \ + curl -fsSL "https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js" -o static/vendor/chartjs-adapter-date-fns.bundle.min.js && \ + curl -fsSL "https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap" -o static/vendor/fonts.css && \ + grep -q 'url(' static/vendor/fonts.css && \ + # Download the actual font files referenced in the CSS + grep -oP 'url\(\K[^)]+' static/vendor/fonts.css | while read url; do \ + FILENAME=$(echo "$url" | sed 's/.*\///;s/?.*//' ); \ + curl -fsSL "$url" -o "static/vendor/${FILENAME}" || exit 1; \ + sed -i "s|${url}|/static/vendor/${FILENAME}|g" static/vendor/fonts.css; \ + done && \ + # noVNC (VM console): the release's ES modules (core/) and its vendored pako, MPL-2.0 + curl -fsSL "https://github.com/novnc/noVNC/archive/refs/tags/v1.5.0.tar.gz" | tar -xz -C /tmp && \ + mkdir -p static/vendor/novnc && \ + cp -r /tmp/noVNC-1.5.0/core /tmp/noVNC-1.5.0/vendor /tmp/noVNC-1.5.0/LICENSE.txt static/vendor/novnc/ && \ + rm -rf /tmp/noVNC-1.5.0 + +COPY dashboard/requirements.txt dashboard/constraints.txt ./ +# constraints.txt: every transitive package at the version this release was tested with +RUN pip install --no-cache-dir -r requirements.txt -c constraints.txt +# the version this image was built from: what the updater reports as installed (the checkout may be newer) +COPY VERSION . COPY dashboard/app.py . COPY dashboard/config_db.py . COPY dashboard/user_db.py . @@ -24,6 +48,7 @@ COPY dashboard/verify_mail.py . COPY dashboard/forwarding.py . COPY dashboard/alerts.py . COPY dashboard/storage_summary.py . +COPY dashboard/vm_rows.py . COPY dashboard/manual.py . COPY dashboard/cluster_registry.py . COPY dashboard/hypercore_tasks.py . @@ -47,23 +72,6 @@ COPY dashboard/templates/ templates/ COPY docs/manual/ manual/ COPY docs/administration.md manual/extra/ -# Download external dependencies for offline/dark-site support -RUN mkdir -p static/vendor && \ - curl -sL "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js" -o static/vendor/chart.umd.min.js && \ - curl -sL "https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js" -o static/vendor/chartjs-adapter-date-fns.bundle.min.js && \ - curl -sL "https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap" -o static/vendor/fonts.css && \ - # Download the actual font files referenced in the CSS - grep -oP 'url\(\K[^)]+' static/vendor/fonts.css | while read url; do \ - FILENAME=$(echo "$url" | sed 's/.*\///;s/?.*//' ); \ - curl -sL "$url" -o "static/vendor/${FILENAME}"; \ - sed -i "s|${url}|/static/vendor/${FILENAME}|g" static/vendor/fonts.css; \ - done && \ - # noVNC (VM console): the release's ES modules (core/) and its vendored pako, MPL-2.0 - curl -sL "https://github.com/novnc/noVNC/archive/refs/tags/v1.5.0.tar.gz" | tar -xz -C /tmp && \ - mkdir -p static/vendor/novnc && \ - cp -r /tmp/noVNC-1.5.0/core /tmp/noVNC-1.5.0/vendor /tmp/noVNC-1.5.0/LICENSE.txt static/vendor/novnc/ && \ - rm -rf /tmp/noVNC-1.5.0 - EXPOSE 5000 # threaded workers: a VM console is a long-lived websocket (/console/ws) that holds one thread for # its duration; sync workers would be blocked by it and killed by their request timeout diff --git a/dashboard/access_api.py b/dashboard/access_api.py index 2676495..39d4c51 100644 --- a/dashboard/access_api.py +++ b/dashboard/access_api.py @@ -30,6 +30,28 @@ def _uuid_or_none(v): return v +def outranks(acc: rbac.Access, target_grants, target_is_admin: bool = False) -> bool: + """May `acc` act on another account itself (password, two-factor, address, enabled, delete)? Whoever sets + a password can sign in as that person, so: a root Admin, or someone who holds every permission the + target holds, at every scope the target holds it (the no-escalation rule of rbac.may_grant, applied to + each of the target's grants). A legacy role='admin' row counts as a root Admin.""" + if acc.is_root_admin(): + return True + if target_is_admin: + return False + for g in target_grants: + if not g.effective(): + continue + ok, _ = rbac.may_grant(acc, g.perms, g.kind, node_id=g.node_id, cluster_id=g.cluster_id, vm_uuid=g.vm_uuid) + if not ok: + return False + return True + + +ACCOUNT_DENIED = ('only an administrator of the whole installation, or a user manager who holds everything this ' + 'account holds, changes this account') + + def register(app, requires, access, clusters, vm_index_rows): """access(): the request's rbac.Access; clusters(): enabled clusters; vm_index_rows(cid): VMs with tags.""" @@ -59,6 +81,15 @@ def top(acc: rbac.Access) -> bool: delete, address, password). Everyone else manages the access people hold in their reach.""" return acc.can('users.manage') + def may_touch_account(acc: rbac.Access, u: dict) -> bool: + """A top-level user manager who also outranks the account (see outranks): a custom root role with + users.manage alone would otherwise set an Admin's password and sign in as them.""" + return top(acc) and outranks(acc, access_db.grants_of_principal(user_id=u['user_id']), u.get('role') == 'admin') + + def require_touch_account(acc: rbac.Access, u: dict) -> None: + if not may_touch_account(acc, u): + raise AccessError(ACCOUNT_DENIED, 403) + def may_manage_group(acc: rbac.Access, g: dict) -> bool: return acc.can('groups.manage', node_id=g.get('node_id')) or acc.can('users.manage', node_id=g.get('node_id')) @@ -124,10 +155,17 @@ def parse_scope(b: dict, tree: rbac.Tree) -> dict: out['vm_name'] = name or str(s.get('vm_name') or '')[:200] or None return out - def grant_check(acc: rbac.Access, r: dict, scope: dict) -> None: + def grant_check(acc: rbac.Access, r: dict, scope: dict, perm: str = 'users.manage') -> None: + """May `acc` hand role `r` to someone on `scope`? Two conditions: they manage people there (`perm` on + the scope: users.manage, or groups.manage when the access comes with a group), and they hold every + permission of the role there themselves. The second alone is not enough: an Admin of customer A who + is a Viewer at customer B holds Viewer's permissions at B, but B's people are not theirs to manage.""" tree = acc.tree if not role_usable_at(r, scope, tree): raise AccessError('that role is not defined for this part of the tree', 403) + if not access_db.assignment_in_reach(acc, {'scope_kind': scope['kind'], 'node_id': scope.get('node_id'), + 'cluster_id': scope.get('cluster_id')}, perm): + raise AccessError('you do not manage access on that scope', 403) tags = [] if scope['kind'] == 'vm': tags = next((v.get('tags') or [] for v in vm_index_rows(scope['cluster_id']) if v.get('uuid') == scope['vm_uuid']), []) @@ -138,7 +176,17 @@ def grant_check(acc: rbac.Access, r: dict, scope: dict) -> None: def visible_roles(acc: rbac.Access) -> list[dict]: nodes = acc.visible_nodes() | acc.nodes_above() - return [r for r in access_db.roles() if r['node_id'] is None or r['node_id'] in nodes or acc.superuser] + vis = seen(acc) + out = [] + for r in access_db.roles(): + if not (r['node_id'] is None or r['node_id'] in nodes or acc.superuser): + continue + if vis is not None and r['node_id'] not in vis: + # defined above the reader (an MSP's or the installation's role): usable, but where it is defined, + # who made it, what it was copied from and how widely it is used are not theirs to know + r = dict(r, node_id=None, created_by=None, copied_from=None, in_use=None, defined_above=True) + out.append(r) + return out def node_payload(acc: rbac.Access) -> list[dict]: visible = acc.visible_nodes() if not acc.is_root_admin() else None @@ -293,6 +341,8 @@ def access_user_update(user_id): kw = {} if ('enabled' in b or 'email' in b) and not top(acc): raise AccessError('only an administrator of the whole installation changes the account itself', 403) + if 'enabled' in b or 'email' in b: + require_touch_account(acc, u) if 'enabled' in b: if u['user_id'] == me_id(): raise AccessError('you cannot disable your own account', 409) @@ -311,6 +361,9 @@ def access_user_update(user_id): raise AccessError('the name is the person\'s own: they or an administrator of the whole installation set it', 403) kw['display_name'] = str(b['display_name'] or '') access_db.update_user(u['user_id'], actor(), **kw) + if 'email' in kw: + import user_db + user_db.bump_session_gen(access_db.normalise_email(kw['email'])) # a new login: the old sessions end return jsonify(dict({'ok': True}, **({'invitation': activation} if activation else {}))) @app.route('/api/access/users/', methods=['DELETE']) @@ -319,6 +372,7 @@ def access_user_delete(user_id): u = managed_user(user_id) if u['user_id'] == me_id(): raise AccessError('you cannot delete your own account', 409) + require_touch_account(access(), u) access_db.delete_user(u['user_id'], actor()) return jsonify({'ok': True}) @@ -338,10 +392,12 @@ def access_user_password(user_id): """Credentials are never a tenant matter (PLAN-roles, Accounts 5): top-level admins only.""" import user_db u = managed_user(user_id) + require_touch_account(access(), u) pw = (request.get_json(silent=True) or {}).get('new_password') or '' if len(pw) < 8: raise AccessError('the password needs at least 8 characters') user_db.set_password(u['username'], pw) + user_db.bump_session_gen(u['username']) # the person's open sessions end with the old password conn = access_db._connect() try: with conn.cursor() as cur: @@ -528,7 +584,7 @@ def access_group_member(group_id): for a in access_db.assignments(group_id=g['group_id']): scope = {'kind': a['scope_kind'], 'node_id': a['node_id'], 'cluster_id': a['cluster_id'], 'tag': a['tag'], 'vm_uuid': a['vm_uuid']} - grant_check(acc, access_db.role(a['role_id']), scope) + grant_check(acc, access_db.role(a['role_id']), scope, 'groups.manage') access_db.set_group_member(g['group_id'], u['user_id'], bool(b.get('member', True)), actor()) return jsonify({'ok': True}) @@ -715,4 +771,5 @@ def covers(x): # the checks the invitations (invite_api) share with this module return SimpleNamespace(grant_check=grant_check, parse_scope=parse_scope, scope_node=scope_node, seen=seen, - nameable=nameable, may_manage_group=may_manage_group, top=top, actor=actor, me_id=me_id) + nameable=nameable, may_manage_group=may_manage_group, top=top, actor=actor, me_id=me_id, + require_touch_account=require_touch_account, access=access) diff --git a/dashboard/access_db.py b/dashboard/access_db.py index 4483a69..ed2f102 100644 --- a/dashboard/access_db.py +++ b/dashboard/access_db.py @@ -15,6 +15,7 @@ import threading import time +import cluster_registry import rbac log = logging.getLogger(__name__) @@ -232,8 +233,8 @@ def _heal_root_admin(cur, user_id: str) -> None: def user_state(user_id: str) -> dict | None: - """{username, enabled, awaiting_access} of a user id, or None when the user no longer exists (cached - briefly: every API call asks).""" + """{username, enabled, awaiting_access, session_gen} of a user id, or None when the user no longer exists + (cached briefly: every API call asks; any change bumps the shared version, which ends the cache).""" now = time.monotonic() ver = _version() with _lock: @@ -244,15 +245,24 @@ def user_state(user_id: str) -> dict | None: try: with conn.cursor() as cur: try: - cur.execute('SELECT username, enabled, awaiting_access FROM config.users WHERE user_id = %s', (user_id,)) + cur.execute('SELECT username, enabled, awaiting_access, session_gen FROM config.users WHERE user_id = %s', + (user_id,)) row = cur.fetchone() except Exception as exc: # noqa: BLE001 if not _missing(exc): raise conn.rollback() - cur.execute('SELECT username, TRUE AS enabled, FALSE AS awaiting_access FROM config.users WHERE user_id = %s', - (user_id,)) - row = cur.fetchone() + try: # before migration 058: no session generation yet + cur.execute('SELECT username, enabled, awaiting_access, 0 AS session_gen FROM config.users WHERE user_id = %s', + (user_id,)) + row = cur.fetchone() + except Exception as exc2: # noqa: BLE001 + if not _missing(exc2): + raise + conn.rollback() + cur.execute('SELECT username, TRUE AS enabled, FALSE AS awaiting_access, 0 AS session_gen ' + 'FROM config.users WHERE user_id = %s', (user_id,)) + row = cur.fetchone() finally: conn.close() state = dict(row) if row else None @@ -316,10 +326,29 @@ def nodes() -> list[dict]: conn.close() +def _colour(value): + """cluster_registry.clean_colour, as an AccessError (400).""" + try: + return cluster_registry.clean_colour(value) + except ValueError as e: + raise AccessError(str(e), 400) from None + + +_CONTROL = re.compile('[\x00-\x1f\x7f\u2028\u2029]') + + +def no_control(value, what: str = 'a name') -> None: + """Names go into mail subjects and texts (invitations, approvals): a line break there makes the mail + library refuse the whole message. Refused where they are entered.""" + if value and _CONTROL.search(str(value)): + raise AccessError(f'{what} cannot contain line breaks or control characters') + + def create_node(name: str, level: str, parent_id: str | None, colour: str | None, actor: str) -> str: name = (name or '').strip() if not name or len(name) > 80: raise AccessError('a name is required (at most 80 characters)') + no_control(name) if level not in rbac.NODE_LEVELS: raise AccessError('unknown level') tree = load_tree() @@ -331,7 +360,7 @@ def create_node(name: str, level: str, parent_id: str | None, colour: str | None with conn.cursor() as cur: try: cur.execute('''INSERT INTO config.folders (name, level, parent_id, colour) VALUES (%s, %s, %s, %s) - RETURNING folder_id::text AS id''', (name, level, parent_id, colour or None)) + RETURNING folder_id::text AS id''', (name, level, parent_id, _colour(colour))) except Exception as exc: # noqa: BLE001 if 'ux_folders_parent_name' in str(exc) or 'duplicate key' in str(exc): raise AccessError(f'there already is a {level} called {name!r} here', 409) from exc @@ -357,6 +386,7 @@ def rename_node(node_id: str, name: str | None, colour, actor: str) -> None: name = name.strip() if not name or len(name) > 80: raise AccessError('a name is required (at most 80 characters)') + no_control(name) try: cur.execute('UPDATE config.folders SET name = %s, updated_at = NOW() WHERE folder_id = %s', (name, node_id)) except Exception as exc: # noqa: BLE001 @@ -365,7 +395,7 @@ def rename_node(node_id: str, name: str | None, colour, actor: str) -> None: raise audit(cur, actor, f"{row['level']}.rename", f"{row['name']} → {name}", node_id=node_id) if colour is not ...: - cur.execute('UPDATE config.folders SET colour = %s, updated_at = NOW() WHERE folder_id = %s', (colour or None, node_id)) + cur.execute('UPDATE config.folders SET colour = %s, updated_at = NOW() WHERE folder_id = %s', (_colour(colour), node_id)) conn.commit() finally: conn.close() @@ -446,6 +476,7 @@ def save_role(role_id: str | None, name: str, description: str, node_id: str | N name = (name or '').strip() if not name or len(name) > 60: raise AccessError('a name is required (at most 60 characters)') + no_control(name) perms = sorted(rbac.expand(perms)) if not perms: raise AccessError('a role needs at least one permission') @@ -530,6 +561,7 @@ def save_group(group_id: str | None, name: str, description: str, node_id: str | name = (name or '').strip() if not name or len(name) > 60: raise AccessError('a name is required (at most 60 characters)') + no_control(name) conn = _connect() try: with conn.cursor() as cur: @@ -695,6 +727,8 @@ def update_user(user_id: str, actor: str, *, enabled=None, display_name=None, em raise AccessError('give the account its access first', 409) if enabled and u['awaiting_email'] and email is None: raise AccessError('give the account its email address first', 409) + if not enabled: + _guard_last_root_admin(cur, removing_user=user_id) # as delete and assignment removal do cur.execute('UPDATE config.users SET enabled = %s, updated_at = NOW() WHERE user_id = %s', (bool(enabled), user_id)) audit(cur, actor, 'user.enable' if enabled else 'user.disable', u['username']) if display_name is not None: @@ -940,14 +974,14 @@ def node_label(node_id, tree: rbac.Tree, visible: set | None = None) -> str: return ' / '.join(tree.name.get(n, n) for n in chain) or str(node_id) -def assignment_in_reach(acc: rbac.Access, a: dict) -> bool: - """May this reader manage people on the scope of assignment `a` (users.manage there)?""" +def assignment_in_reach(acc: rbac.Access, a: dict, perm: str = 'users.manage') -> bool: + """May this reader manage people on the scope of assignment `a` (`perm` there, users.manage by default)?""" k = a['scope_kind'] if k == 'node': - return acc.can('users.manage', node_id=a['node_id']) + return acc.can(perm, node_id=a['node_id']) if k in ('cluster', 'tag', 'vm'): - return acc.can('users.manage', a['cluster_id']) - return acc.can('users.manage') # root: the whole installation + return acc.can(perm, a['cluster_id']) + return acc.can(perm) # root: the whole installation def manageable_user_ids(acc: rbac.Access) -> set | None: diff --git a/dashboard/account_api.py b/dashboard/account_api.py index 5ed37f6..8182fbe 100644 --- a/dashboard/account_api.py +++ b/dashboard/account_api.py @@ -16,6 +16,7 @@ import hashlib import secrets +import threading from flask import jsonify, render_template, request, session @@ -174,6 +175,11 @@ def page(state, status=200, **vals): def account_forgot(): if not mailer.configured(): return page('no_mail') + base = mailer.link_base() + if not base: + # the link is never built from this request's Host header (anyone can set it): no address, no link + app.logger.warning('password reset by mail is off: %s', mailer.LINK_ADDRESS_MISSING) + return page('no_mail') if request.method == 'GET': return page('forgot') raw = request.form.get('email', '') @@ -185,10 +191,19 @@ def account_forgot(): u = access_db.user(uid) if uid else None # only an enabled account with a confirmed address, and not more than a few links an hour if u and u['enabled'] and not u['awaiting_email'] and '@' in u['username'] and _recent_resets(uid) < RESETS_PER_HOUR: - token = _new_token('reset', uid, RESET_MINUTES) - link = f"{mailer.link_base(request.host_url)}/account/reset/{token}" - mailer.deliver(u['username'], 'reset', _lang(), by=u['username'], link=link, minutes=RESET_MINUTES) - _audit(u['username'], 'user.reset_requested', u['username']) + # in the background: the SMTP conversation takes seconds, and an answer that slow only for addresses + # with an account would tell which addresses have one + lang = _lang() + token = _new_token('reset', uid, RESET_MINUTES) # here: the hourly limit counts these rows + + def send(): + try: + mailer.deliver(u['username'], 'reset', lang, by=u['username'], link=f"{base}/account/reset/{token}", + minutes=RESET_MINUTES) + _audit(u['username'], 'user.reset_requested', u['username']) + except Exception: # noqa: BLE001 + app.logger.warning('password reset mail for %s failed', u['username'], exc_info=True) + threading.Thread(target=send, daemon=True, name='reset-mail').start() return page('forgot_sent', email=email) @app.route('/account/reset/', methods=['GET', 'POST']) @@ -208,6 +223,7 @@ def account_reset(token): return page('invalid', 404) import user_db user_db.set_password(tok['username'], pw) + user_db.bump_session_gen(tok['username']) # whoever held a session with the old password is out _audit(tok['username'], 'user.password_reset_self', tok['username']) session.clear() return page('reset_done') @@ -231,7 +247,9 @@ def account_email_change(): if not mailer.configured(): raise AccessError('changing your address needs mail, which is not set up here: ask an administrator', 409) token = _new_token('email', session['user_id'], EMAIL_MINUTES, new_email=new) - link = f"{mailer.link_base(request.host_url)}/account/email/{token}" + # the person asked from their own signed-in browser, with their password, for a mail to an address they + # typed: the address they reach HCM on is a fair fallback here (never on the public routes) + link = f"{mailer.link_base() or request.host_url.rstrip('/')}/account/email/{token}" r = mailer.deliver(new, 'email_confirm', b.get('lang') or _lang(), by=me, link=link, minutes=EMAIL_MINUTES, new=new) _audit(me, 'user.email_requested', me, detail={'to': new}) if not r['sent']: @@ -253,6 +271,8 @@ def account_email_confirm(token): access_db.change_address(tok['user_id'], new, actor=old, verified=True) except AccessError: return page('email_taken', new=new) + import user_db + user_db.bump_session_gen(new) mailer.deliver(old, 'email_notice', _lang(), by=new, new=new) if session.get('user_id') == tok['user_id']: session.clear() @@ -274,6 +294,9 @@ def account_me_password(): if len(new) < 8: raise AccessError('the password needs at least 8 characters') user_db.set_password(me, new) + gen = user_db.bump_session_gen(me) # every other session of this account ends; this one goes on + if gen is not None: + session['gen'] = gen _audit(me, 'user.password_changed_self', me) return jsonify({'ok': True}) @@ -297,7 +320,9 @@ def account_otp_reset(user_id): raise AccessError('not found', 404) if u['user_id'] == h.me_id(): raise AccessError('turn off your own two-factor on your Account page', 409) + h.require_touch_account(h.access(), u) # resetting someone's 2FA is half of signing in as them user_db.disable_otp(u['username']) + user_db.bump_session_gen(u['username']) _audit(h.actor(), 'user.otp_reset', u['username']) access_db.invalidate() return jsonify({'ok': True}) diff --git a/dashboard/app.py b/dashboard/app.py index 9c0a432..f648528 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -54,13 +54,14 @@ import psycopg2 import psycopg2.extras from flask import Flask, g, jsonify, redirect, render_template, request, send_from_directory, Response, session, url_for -from flask_cors import CORS +from flask.sessions import SecureCookieSessionInterface from flask_sock import Sock import simple_websocket from influxdb_client import InfluxDBClient import config_db import user_db import backup_scope +import vm_rows import rbac import access_db import cluster_registry @@ -72,7 +73,28 @@ from alerts import ALERT_LEVELS, ALERT_SEVERITY, active_items, condition_episodes, ms_iso app = Flask(__name__, static_folder='static', template_folder='templates') -CORS(app) +# No CORS: every page that calls this API is served by it (the guest pages too), so no other origin needs to +# read its answers. The session cookie is not sent on cross-site requests (SameSite=Lax), and is marked Secure +# when the request came over HTTPS (directly or through a TLS proxy), so plain-HTTP installs keep working. +app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' +app.config['SESSION_COOKIE_SECURE'] = os.getenv('HCM_SESSION_COOKIE_SECURE', '').strip().lower() in ('1', 'true', 'yes') + + +def _request_is_https() -> bool: + return request.is_secure or request.headers.get('X-Forwarded-Proto', '').split(',')[0].strip().lower() == 'https' + + +class _SessionInterface(SecureCookieSessionInterface): + def get_cookie_secure(self, app): # called while the response of a request is made + if app.config.get('SESSION_COOKIE_SECURE'): + return True + try: + return _request_is_https() + except RuntimeError: # outside a request + return False + + +app.session_interface = _SessionInterface() # websockets (VM console): pings keep reverse proxies with a read timeout from closing an idle console app.config['SOCK_SERVER_OPTIONS'] = {'ping_interval': 25, 'max_message_size': None} sock = Sock(app) @@ -105,9 +127,41 @@ def theme_inline(): # fallback stale threshold — live value is read from config_db per request STALE_SECONDS = int(os.getenv('SC_DASHBOARD_STALE_SECONDS', 120)) -# session signing key — generated randomly at startup if not set (sessions won't -# survive restarts in that case, but everything still works for dev) -_secret_key = os.getenv('SC_DASHBOARD_SECRET_KEY', '') or secrets.token_hex(32) +_PLACEHOLDER_SECRETS = ('HCM_SECRET_KEY', 'SC_DASHBOARD_SECRET_KEY', 'SC_DASHBOARD_PASSWORD') + + +def _placeholder_secrets(env=os.environ) -> list[str]: + """The secrets still set to the .env.template placeholder: a key everyone knows signs everyone's sessions + (or decrypts the stored cluster passwords), and the first admin would get a password everyone knows.""" + return [k for k in _PLACEHOLDER_SECRETS if (env.get(k) or '').strip() == 'CHANGE_ME'] + + +def _session_secret(env=os.environ) -> str: + """SC_DASHBOARD_SECRET_KEY, else one derived from HCM_SECRET_KEY: the four gunicorn workers must sign with + the same key (a random key per worker made a login work only on the worker that issued it).""" + key = (env.get('SC_DASHBOARD_SECRET_KEY') or '').strip() + if key: + return key + base = (env.get(hcm_crypto.ENV_VAR) or '').strip() + if base: + return hmac.new(base.encode(), b'hcm-internal:dashboard-session', hashlib.sha256).hexdigest() + app.logger.warning('neither SC_DASHBOARD_SECRET_KEY nor %s is set: each worker signs sessions with its own random ' + 'key, so logins fail now and then; set SC_DASHBOARD_SECRET_KEY in .env', hcm_crypto.ENV_VAR) + return secrets.token_hex(32) + + +_placeholders = _placeholder_secrets() +if _placeholders: + _msg = (f"refusing to start: {', '.join(_placeholders)} in .env still has the placeholder CHANGE_ME. Set each to a " + 'long random value (python3 -c "import secrets; print(secrets.token_hex(32))"; for SC_DASHBOARD_PASSWORD ' + 'the first admin\'s password), then start the stack again.') + import sys as _sys + print(_msg, file=_sys.stderr, flush=True) + app.logger.critical(_msg) + raise SystemExit(_msg) + +# session signing key: the same in every worker and across restarts +_secret_key = _session_secret() app.secret_key = _secret_key # bootstrap the users table and seed the admin account from env vars on first run @@ -121,9 +175,39 @@ def theme_inline(): except Exception as _exc: # noqa: BLE001 — before migration 046, or the database is not up yet app.logger.info('email address check skipped: %s', _exc) -# auth is enabled iff at least one user row exists. Cached at startup — restart -# is required if the table goes from empty to populated outside of the UI -_AUTH_ENABLED = user_db.has_any_users() +# auth is enabled iff at least one user row exists. Cached once the database has answered — restart +# is required if the table goes from empty to populated outside of the UI. Until it has answered +# (Postgres still starting, or down) authentication stays ON: an unreachable database is not "no users". +_AUTH_ENABLED = True +_auth_known = False +_auth_checked_at = 0.0 +_auth_lock = threading.Lock() + + +def _refresh_auth_enabled(min_interval: float = 5.0) -> None: + """Ask the database whether accounts exist, until it has answered once. While the answer is unknown + every request is treated as needing a login; the question is repeated at most every few seconds.""" + global _AUTH_ENABLED, _auth_known, _auth_checked_at + if _auth_known: + return + with _auth_lock: + if _auth_known or time.monotonic() - _auth_checked_at < min_interval: + return + first = _auth_checked_at == 0.0 + _auth_checked_at = time.monotonic() + if not first: + # the start-up bootstrap ran against a database that was not there: do it now, before + # concluding that there are no accounts + user_db.ensure_table() + user_db.seed_admin_from_env() + state = user_db.has_any_users() + if state is None: + app.logger.warning('user store unreachable: logins stay required until it answers') + return + _AUTH_ENABLED, _auth_known = bool(state), True + + +_refresh_auth_enabled() class AccessDenied(Exception): @@ -169,9 +253,24 @@ def _login_problem(): if request.path.startswith('/api/'): return jsonify({'error': 'Your account is waiting for an administrator to assign its access'}), 401 return redirect(url_for('login_page')) + if int(state.get('session_gen') or 0) != int(session.get('gen') or 0): + # the account's sessions were ended (password changed or reset, two-factor off or reset, new address): + # a cookie from before, also a stolen one, no longer signs in + session.clear() + if request.path.startswith('/api/'): + return jsonify({'error': 'Authentication required'}), 401 + return redirect(url_for('login_page')) return None +def _start_session(u: dict) -> None: + """Sign `u` in on this session (after the password, and the code when two-factor is on).""" + session['user_id'] = str(u['user_id']) + session['username'] = u['username'] + session['role'] = u['role'] + session['gen'] = int(u.get('session_gen') or 0) + + _ROUTE_PERMS: dict = {} # view function name -> (permission or None, scope); read by /api/access/routes @@ -202,13 +301,12 @@ def wrapped(*args, **kwargs): elif scope == 'any': ok = acc.held_anywhere(perm) else: + problem = _write_cluster_problem(perm, need=True) + if problem is not None: + return problem + # reads fall back to the first allowed cluster (the UI recovers after a cluster was taken + # away); a write was checked above: it names a cluster the user may use for this route ok = bool(_visible_clusters(perm)) - wanted = (request.args.get('cluster') or '').strip() - if ok and wanted and cluster_registry.is_uuid(wanted) and \ - wanted not in {c.cluster_id for c in _visible_clusters(perm)}: - # reads fall back to the first allowed cluster (the UI recovers after a cluster was - # taken away); anything that changes something is refused - ok = request.method in ('GET', 'HEAD') if not ok: if request.path.startswith('/api/'): return jsonify({'error': 'Access denied', 'permission': perm}), 403 @@ -230,8 +328,74 @@ def deco(f): return deco +_UNSAFE_METHODS = frozenset({'POST', 'PUT', 'PATCH', 'DELETE'}) + + +def _host_of(url_or_host: str) -> str: + """'https://Hcm.Example:443/x' -> 'hcm.example' (scheme and default ports left out: a TLS proxy changes + the scheme, not who the site is).""" + v = (url_or_host or '').strip().lower() + if '://' in v: + v = urllib.parse.urlsplit(v).netloc + v = v.rsplit('@', 1)[-1] + for port in (':80', ':443'): + if v.endswith(port): + v = v[:-len(port)] + return v + + +def _own_hosts() -> set: + """The names this request may legitimately come from: the Host it was sent to and the one a reverse proxy + names in X-Forwarded-Host (a cross-site page can set neither: X-Forwarded-Host is not a header a browser + lets another origin add without a CORS preflight, which this app never answers).""" + hosts = {_host_of(request.host)} + fwd = (request.headers.get('X-Forwarded-Host') or '').split(',')[0].strip() + if fwd: + hosts.add(_host_of(fwd)) + return hosts + + +def _configured_hosts() -> set: + """The addresses in Settings -> Mail (links and guest links): a proxy that rewrites Host still works.""" + import mailer + out = set() + try: + s = mailer.settings() + for k in ('public_url', 'guest_url'): + if s.get(k): + out.add(_host_of(s[k])) + except Exception: # noqa: BLE001 — no database: only the request's own host counts + pass + env = (os.getenv('HCM_GUEST_BASE_URL') or '').strip() + if env: + out.add(_host_of(env)) + return out + + +@app.before_request +def _same_origin_only(): + """Cross-site request forgery: a request that changes something must come from a page of this site. + Browsers send Origin on such requests (Referer when they leave Origin out); a value naming another site is + refused. A request with neither is a script or a non-browser client, which holds no victim's cookie.""" + if request.method not in _UNSAFE_METHODS or request.path.startswith('/internal/'): + return None + source = request.headers.get('Origin') + if source is None: + source = request.headers.get('Referer') + if not source: + return None + source_host = _host_of(source) if source != 'null' else 'null' + if source_host and (source_host in _own_hosts() or source_host in _configured_hosts()): + return None + app.logger.warning('refused a cross-site %s %s from %r', request.method, request.path, source[:200]) + if request.path.startswith('/api/'): + return jsonify({'error': 'cross-site request refused'}), 403 + return Response('Cross-site request refused', status=403, mimetype='text/plain') + + @app.before_request def _access_fresh(): + _refresh_auth_enabled() access_db.begin_request() @@ -240,8 +404,10 @@ def _access_denied(e): return jsonify({'error': str(e)}), e.status -def get_influx_client(): - return InfluxDBClient(url=INFLUX_URL, token=INFLUX_TOKEN, org=INFLUX_ORG) +def get_influx_client(timeout: int | None = None): + """timeout: milliseconds per query (the client's default is 10 s).""" + kw = {'timeout': timeout} if timeout else {} + return InfluxDBClient(url=INFLUX_URL, token=INFLUX_TOKEN, org=INFLUX_ORG, **kw) # --------------------------------------------------------------------------- @@ -321,6 +487,15 @@ def _hours_arg(default: int = 1) -> int: raise BadRequest(f'hours must be a whole number of hours, not {raw!r}') +def _int_arg(name: str, default: int, lo: int, hi: int) -> int: + """?name= as a whole number clamped to lo..hi; anything else is the caller's mistake (400), not a 500.""" + raw = request.args.get(name, str(default)) + try: + return max(lo, min(int(raw), hi)) + except (TypeError, ValueError): + raise BadRequest(f'{name} must be a whole number, not {raw!r}') + + @app.errorhandler(BadRequest) def _bad_request(e): return jsonify({'error': str(e)}), 400 @@ -354,6 +529,21 @@ def _cluster_id() -> str: return visible[0].cluster_id if visible else cluster_registry.TEMPLATE_CLUSTER_ID +def _write_cluster_problem(perm: str, need: bool): + """For a request that changes something on a cluster: the cluster in ?cluster= must be one the user may use + for `perm` (403), and with `need` it must be there at all (400). Never the first visible cluster instead: + a write that names no cluster, or one taken away, would otherwise act on some other cluster. Reads are not + checked here (they fall back, so the UI recovers). Returns an error response or None.""" + if request.method in ('GET', 'HEAD', 'OPTIONS'): + return None + wanted = (request.args.get('cluster') or '').strip() + if not wanted: + return (jsonify({'error': 'cluster is required'}), 400) if need else None + if not cluster_registry.is_uuid(wanted) or wanted not in {c.cluster_id for c in _visible_clusters(perm)}: + return jsonify({'error': 'Access denied', 'permission': perm}), 403 + return None + + def _named_cluster(perm: str) -> str: """The cluster in ?cluster= when the user holds `perm` on the whole of it; refused otherwise.""" wanted = (request.args.get('cluster') or '').strip() or _cluster_id() @@ -500,15 +690,22 @@ def get_nodes(): if 'num_threads' not in nodes[node_uuid]: nodes[node_uuid]['num_threads'] = int(record.values.get('num_threads') or 0) - # fetch latest allocated vCPUs per node from vm_inventory + # fetch latest allocated vCPUs per node from vm_inventory. Node and state are tags, so a VM that + # migrated or stopped inside the hour has several series: only its newest one counts, or it would be + # added to every node it ran on + # (and only the last polls are read, as in _vm_sizes: a deleted VM stops counting when it stops reporting) + fresh = max(60, int(_stale_seconds())) vcpu_query = f''' from(bucket: "{INFLUX_BUCKET}") - |> range(start: -1h) + |> range(start: -{fresh}s) {_flux_cluster()} |> filter(fn: (r) => r["_measurement"] == "vm_inventory") |> filter(fn: (r) => r["_field"] == "num_vcpu") - |> filter(fn: (r) => r["vm_state"] == "RUNNING") |> last() + |> group(columns: ["vm_uuid"]) + |> sort(columns: ["_time"]) + |> last() + |> filter(fn: (r) => r["vm_state"] == "RUNNING") |> group(columns: ["node_uuid"]) |> sum() ''' @@ -558,9 +755,8 @@ def _vm_sizes(client, vms: dict) -> None: """Adds mem_bytes, num_vcpu, os, state and disk_bytes to each VM of the list, and the VMs that are not running (from vm_inventory, which lists every VM). Memory and vCPUs come from vm_inventory; a VM's disks from its per-disk I/O samples (vsd_metrics carry vm_uuid and vsd_uuid), - their sizes from block_device_metrics by vsd_uuid. CD-ROMs (mounted ISOs) do not count.""" - if not vms: - return + their sizes from block_device_metrics by vsd_uuid. CD-ROMs (mounted ISOs) do not count. + Also when no VM is running (a passive DR cluster): the stopped ones are still listed.""" q = client.query_api() # the inventory as of the last polls only: a deleted VM drops out as fast as a stopped one shows up fresh = max(60, int(_stale_seconds())) @@ -626,35 +822,10 @@ def get_vms(): ''' result = client.query_api().query(org=INFLUX_ORG, query=query) - vms = {} - for table in result: - for record in table.records: - vm_uuid = record.values.get('vm_uuid', 'unknown') - vm_name = record.values.get('vm_name', 'Unknown') - node_uuid = record.values.get('node_uuid', 'unknown') - - # skip records from in-flight migration state (no node assignment yet) - if node_uuid == 'unknown': - continue + # one row per VM, described as of its newest sample: a VM that migrated inside the range has a + # series per node and belongs to the node it is on now (vm_rows.py) + vms = vm_rows.fold((record.get_time(), record.values) for table in result for record in table.records) - if vm_uuid not in vms: - vms[vm_uuid] = { - 'uuid': vm_uuid, - 'name': vm_name, - 'node_uuid': node_uuid, - 'node_peer_id': record.values.get('node_peer_id', 'unknown'), - 'tag': record.values.get('vm_tag', ''), - 'vlan': record.values.get('vm_vlan', '0'), - 'history': [] - } - - vms[vm_uuid]['history'].append({ - 'time': record.get_time().isoformat(), - 'cpu_usage': record.values.get('cpu_usage'), - 'rx_bit_rate': record.values.get('rx_bit_rate'), - 'tx_bit_rate': record.values.get('tx_bit_rate') - }) - # fetch true current CPU per VM (last measurement, independent of time range) current_query = f''' from(bucket: "{INFLUX_BUCKET}") @@ -665,11 +836,12 @@ def get_vms(): |> last() ''' current_result = client.query_api().query(org=INFLUX_ORG, query=current_query) - for table in current_result: - for record in table.records: - vid = record.values.get('vm_uuid', 'unknown') - if vid in vms: - vms[vid]['current_cpu'] = record.get_value() + # a VM that migrated in the last 5 minutes has a last() on its old node too: the newest one counts + current = vm_rows.newest_per((record.get_time(), record.values, record.get_value()) + for table in current_result for record in table.records) + for vid, cpu in current.items(): + if vid in vms: + vms[vid]['current_cpu'] = cpu # filter out VMs that haven't reported recently (deleted/stopped) stale_secs = _stale_seconds() @@ -767,34 +939,10 @@ def get_vsds(): |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") ''' result = client.query_api().query(org=INFLUX_ORG, query=query) - - vsds = {} - for table in result: - for record in table.records: - vsd_uuid = record.values.get('vsd_uuid', 'unknown') - - if vsd_uuid not in vsds: - vsds[vsd_uuid] = { - 'uuid': vsd_uuid, - 'name': record.values.get('vsd_name', 'unknown'), - 'type': record.values.get('vsd_type', 'unknown'), - 'vm_uuid': record.values.get('vm_uuid', 'unknown'), - 'vm_name': record.values.get('vm_name', 'Unknown'), - 'node_uuid': record.values.get('node_uuid', 'unknown'), - 'history': [] - } - - vsds[vsd_uuid]['history'].append({ - 'time': record.get_time().isoformat(), - 'read_kbps': record.values.get('read_kbps'), - 'write_kbps': record.values.get('write_kbps'), - 'read_latency_us': record.values.get('read_latency_us'), - 'write_latency_us': record.values.get('write_latency_us'), - 'read_iops': record.values.get('read_iops'), - 'write_iops': record.values.get('write_iops'), - 'capacity_bytes': record.values.get('capacity_bytes'), - }) - + + # one row per disk, described as of its newest sample (its VM may have moved node: vm_rows.py) + vsds = vm_rows.fold_vsds((record.get_time(), record.values) for table in result for record in table.records) + # filter out VSDs that haven't reported recently stale_secs = _stale_seconds() active = [v for v in vsds.values() if not is_stale(v['history'], stale_secs)] @@ -1196,11 +1344,17 @@ def get_config(): @app.route('/api/config', methods=['POST']) @requires('cluster.settings', 'any') def post_config(): - """Update one or more tunables. Accepts {key: value, ...} JSON body.""" + """Update one or more tunables. Accepts {key: value, ...} JSON body. Every value is cast and + range-checked before anything is stored: one value no reader can cast (an emptied number + field arrived as null and was stored as 'None') cost the cluster all its settings.""" try: - updates = request.get_json(force=True) + updates = request.get_json(force=True, silent=True) if not isinstance(updates, dict): return jsonify({'error': 'Expected a JSON object'}), 400 + try: + updates = {k: config_db.validate(k, v) for k, v in updates.items()} + except ValueError as e: + return jsonify({'error': str(e)}), 400 acc = _access() if request.args.get('cluster') == 'defaults': if not acc.can('install.manage'): @@ -1244,7 +1398,7 @@ def _rail_folders(acc, folders: list) -> list: path=(tree.path(fid) if see_all else acc.path(fid))[:-1], # never the layers above the user can_manage_tree=acc.can('tree.manage', node_id=fid), can_manage_clusters=acc.can('cluster.manage', node_id=fid), - can_assign_share=acc.can('backup.targets.manage', node_id=fid))) + can_assign_share=acc.can('backup.targets.manage'))) # targets are listed at root only return out @@ -1256,6 +1410,18 @@ def _cluster_payload(c, extras=None): return d +def _audit(action: str, target: str, node_id: str | None = None, detail: dict | None = None, + actor: str | None = None) -> None: + """One row in the access audit (Settings -> Access -> Audit), best effort: a failed audit write is logged + and never fails the action it describes. node_id: where in the tree it happened (who may read the row).""" + try: + with _pg() as conn, conn.cursor() as cur: + access_db.audit(cur, actor or session.get('username') or ('anonymous' if not _AUTH_ENABLED else 'system'), + action, str(target)[:300], node_id=node_id, detail=detail) + except Exception as exc: # noqa: BLE001 + app.logger.warning('audit %s %s not written: %s', action, target, exc) + + def _set_cluster_role(cluster_id: str, role: str) -> None: """A DR cluster is normally passive: its backup proxies verify restore points around the clock.""" with _pg() as conn, conn.cursor() as cur: @@ -1349,7 +1515,7 @@ def _cluster_form(body: dict) -> dict: @app.route('/api/clusters', methods=['POST']) @requires('cluster.manage', 'any') def api_clusters_create(): - body = request.get_json(force=True, silent=True) or {} + body = request.get_json(silent=True) or {} target_folder = (body.get('folder_id') or '').strip() or None if target_folder and not cluster_registry.is_uuid(target_folder): return jsonify({'error': 'invalid folder id'}), 400 @@ -1388,6 +1554,8 @@ def api_clusters_create(): verify_tls=f['verify_tls'], colour=f['colour'], hc_cluster_uuid=hc_uuid, api_version=f['api_version'], api_v2_available=probe.get('api_v2') if probe.get('ok') else None, hc_version=probe.get('version') or None, folder_id=target_folder) + except ValueError as e: + return jsonify({'error': str(e)}), 400 except Exception as e: msg = str(e) if 'ux_clusters_folder_name' in msg or 'duplicate key' in msg: @@ -1397,6 +1565,8 @@ def api_clusters_create(): cluster_registry.upsert_nodes(cid, probe_nodes, seed_host=f['host']) if probe.get('timezone'): cluster_registry.mark_seen(cid, timezone=probe['timezone']) + _audit('cluster.register', f['name'], node_id=target_folder, + detail={'cluster_id': cid, 'host': f['host'], 'forced': bool(body.get('force')) and not probe.get('ok')}) _invalidate_registry_cache() c = cluster_registry.get(cid) return jsonify({'ok': True, 'cluster': _cluster_payload(c), 'probe': probe}), 201 @@ -1405,12 +1575,13 @@ def api_clusters_create(): @app.route('/api/clusters/', methods=['PUT']) @requires('cluster.manage', 'any') def api_clusters_update(cluster_id): - if not cluster_registry.get(cluster_id): + before = cluster_registry.get(cluster_id) + if not before: return jsonify({'error': 'cluster not found'}), 404 acc = _access() if not acc.can('cluster.manage', cluster_id): return jsonify({'error': 'cluster not found'}), 404 - body = request.get_json(force=True, silent=True) or {} + body = request.get_json(silent=True) or {} if 'folder_id' in body and not _may_move_cluster(acc, cluster_id, body['folder_id'] or None): return jsonify({'error': 'Access denied'}), 403 fields = {} @@ -1426,7 +1597,8 @@ def api_clusters_update(cluster_id): if role is not None and role not in ('production', 'dr'): return jsonify({'error': "role must be 'production' or 'dr'"}), 400 try: - cluster_registry.update(cluster_id, **fields) + if cluster_registry.update(cluster_id, **fields) == 0: + return jsonify({'error': 'cluster not found'}), 404 # removed: not changed, not enabled again if role is not None: _set_cluster_role(cluster_id, role) except ValueError as e: @@ -1436,20 +1608,52 @@ def api_clusters_update(cluster_id): if 'ux_clusters_folder_name' in msg or 'duplicate key' in msg: return jsonify({'error': 'that folder already has a cluster with that name'}), 409 return jsonify({'error': msg}), 500 + changed = sorted(k for k in fields if k != 'folder_id' and (k != 'password' or fields[k])) + if role is not None: + changed.append('role') + if changed: + detail = {'cluster_id': cluster_id, 'fields': changed} + if 'host' in fields: + detail.update(host_from=before.host, host_to=fields['host']) + if 'enabled' in fields: + detail['enabled'] = fields['enabled'] + _audit('cluster.edit', before.name, node_id=before.folder_id, detail=detail) + if 'folder_id' in fields and (fields['folder_id'] or None) != (before.folder_id or None): + _audit('cluster.move', before.name, node_id=fields['folder_id'] or before.folder_id, + detail={'cluster_id': cluster_id, 'from': before.folder_id, 'to': fields['folder_id']}) _invalidate_registry_cache() return jsonify({'ok': True, 'cluster': _cluster_payload(cluster_registry.get(cluster_id))}) +def _backup_chain_count(cluster_id: str) -> int: + """Backup chains in the catalogue for this cluster (0 before the backup schema exists).""" + try: + with _pg() as conn, conn.cursor() as cur: + cur.execute('SELECT COUNT(*) AS n FROM backup.chains WHERE cluster_id = %s', (cluster_id,)) + return int(cur.fetchone()['n']) + except psycopg2.Error as exc: + if getattr(exc, 'pgcode', None) == '42P01': + return 0 + raise + + @app.route('/api/clusters/', methods=['DELETE']) @requires('cluster.manage', 'any') def api_clusters_delete(cluster_id): - if not cluster_registry.get(cluster_id) or not _access().can('cluster.manage', cluster_id): + c = cluster_registry.get(cluster_id) + if not c or not _access().can('cluster.manage', cluster_id): return jsonify({'error': 'cluster not found'}), 404 purge = request.args.get('purge') == '1' + if purge and _backup_chain_count(cluster_id): + # purging cascades to the backup catalogue (chains, points): the data would stay on the target with + # nothing left that knows it is there + return jsonify({'error': 'this cluster still has backups in the catalogue: delete its backup chains first ' + '(Backup -> Restore points), or remove the cluster without purging'}), 409 try: cluster_registry.delete(cluster_id, purge=purge) except Exception as e: return jsonify({'error': str(e)}), 500 + _audit('cluster.purge' if purge else 'cluster.remove', c.name, node_id=c.folder_id, detail={'cluster_id': cluster_id}) _invalidate_registry_cache() return jsonify({'ok': True, 'purged': purge}) @@ -1458,7 +1662,7 @@ def api_clusters_delete(cluster_id): @requires('cluster.manage', 'any') def api_clusters_test_new(): """Connection test for the add/edit form (credentials from the body).""" - f = _cluster_form(request.get_json(force=True, silent=True) or {}) + f = _cluster_form(request.get_json(silent=True) or {}) if not (f['host'] and f['username']): return jsonify({'ok': False, 'error': 'host and username are required'}), 400 return jsonify(cluster_registry.test_connection(f['host'], f['username'], f['password'], f['verify_tls'])) @@ -1594,7 +1798,7 @@ def api_folders_list(): @app.route('/api/folders', methods=['POST']) @requires('tree.manage', 'any') def api_folders_create(): - body = request.get_json(force=True, silent=True) or {} + body = request.get_json(silent=True) or {} acc = _access() parent = (body.get('parent_id') or '').strip() or None if parent is None: @@ -1622,16 +1826,32 @@ def api_folders_update(folder_id): acc = _access() if not acc.can('tree.manage', node_id=folder_id): return jsonify({'error': 'Access denied'}), 403 - body = request.get_json(force=True, silent=True) or {} - if 'share_id' in body and not acc.can('backup.targets.manage', node_id=folder_id): - return jsonify({'error': 'Access denied'}), 403 + body = request.get_json(silent=True) or {} + share = ... + if 'share_id' in body: + # a folder's backup target decides where its VMs' backups are written: targets are an installation + # matter (listed to root target managers only), so a folder admin may not pick one, not even by id + if not acc.can('backup.targets.manage'): + return jsonify({'error': 'Access denied'}), 403 + share = body['share_id'] + if share not in (None, '', 0): + try: + share = int(share) + except (TypeError, ValueError): + return jsonify({'error': 'share_id must be a backup target id'}), 400 try: - cluster_registry.update_folder(folder_id, name=body.get('name'), colour=body.get('colour'), - share_id=body['share_id'] if 'share_id' in body else ...) + cluster_registry.update_folder(folder_id, name=body.get('name'), colour=body.get('colour'), share_id=share) + except ValueError as e: + return jsonify({'error': str(e)}), 400 except Exception as e: if 'ux_folders_name' in str(e) or 'duplicate key' in str(e): return jsonify({'error': 'a folder with that name already exists'}), 409 + if 'foreign key' in str(e).lower() and 'share' in str(e).lower(): + return jsonify({'error': 'no such backup target'}), 404 return jsonify({'error': str(e)}), 500 + if share is not ...: + _audit('folder.target', acc.tree.name.get(folder_id, folder_id), node_id=folder_id, + detail={'target_id': share if share not in (None, '', 0) else None}) _invalidate_registry_cache() return jsonify({'ok': True}) @@ -1661,7 +1881,23 @@ def api_folders_delete(folder_id): # keys that would reveal a target's path or account to a non-admin; the UI shows alias/folder only _BACKUP_SENSITIVE_KEYS = frozenset({'base', 'user', 'username', 'path_uri_base', 'prune_path', 'smb_user', - 'source_uri', 'uri_base', 'uri'}) + 'source_uri', 'uri_base', 'uri', 'effective_base'}) +# who did something, in the backup service's answers: names above the reader are not shown (as elsewhere) +_BACKUP_NAME_KEYS = ('created_by', 'requested_by', 'updated_by', 'muted_by') + + +def _hide_backup_names(obj, names): + """Every dict in a backup API answer: the _BACKUP_NAME_KEYS the reader may not see named become None.""" + if isinstance(obj, list): + for v in obj: + _hide_backup_names(v, names) + elif isinstance(obj, dict): + if any(k in obj for k in _BACKUP_NAME_KEYS): + access_db.hide_names([obj], _BACKUP_NAME_KEYS, names) + for v in obj.values(): + if isinstance(v, (dict, list)): + _hide_backup_names(v, names) + return obj def _strip_sensitive(obj): @@ -1700,9 +1936,13 @@ def _proxy_image_version() -> str | None: def _internal_token_ok() -> bool: + """Bearer BACKUP_API_TOKEN. Without a token configured nothing is accepted: these routes are reachable on + the dashboard's public port and hand out the proxy image (with its token-checking code).""" _, token = _backup_env() + if not token: + return False auth = request.headers.get('Authorization', '') - return not token or auth == f'Bearer {token}' + return hmac.compare_digest(auth.encode(), f'Bearer {token}'.encode()) @app.route('/internal/proxy-image/version') @@ -1902,10 +2142,10 @@ def _tag_guard(cid: str, vm: str | None, payload: dict, kind: str) -> str | None return None touched = (old ^ new) & set(scoped) elif kind == 'clone': - new = set() - for o in payload.get('ops') or []: - if 'tags' in (o or {}): - new = _tags_of(o['tags']) + # the backup service clones from ops[0] only (and a clone set has one op: _backup_check refuses more) + ops = payload.get('ops') or [] + first = ops[0] if ops and isinstance(ops[0], dict) else {} + new = _tags_of(first.get('tags')) touched = (new - old) & set(scoped) elif kind == 'create': touched = _tags_of(((payload.get('spec') or {}).get('tags'))) & set(scoped) @@ -1967,6 +2207,12 @@ def _backup_check(method: str, sub: str, cid: str, payload: dict | None): vm = str(payload.get('vm_uuid') or '') if not vm: return None, (jsonify({'error': 'vm_uuid required'}), 400) + ops = payload.get('ops') + if ops is not None and not isinstance(ops, list): + return None, (jsonify({'error': 'ops must be a list'}), 400) + if str(payload.get('kind') or 'edit') in ('clone', 'snapshot') and len(ops or []) > 1: + # the service acts on the first op only: what the guard checks must be all there is + return None, (jsonify({'error': 'a clone or snapshot is one operation'}), 400) ok = all(_can_vm(p, body_cid, vm) for p in _vmchange_perms(payload)) if not ok: return None, denied @@ -2031,6 +2277,34 @@ def _narrow_backup(sub: str, data, scope, cid: str): return data +# writes that create or change a VM's backup plan (directly, or by adding the VM to a schedule) +_PLAN_WRITE_RE = re.compile(r'plans|plans/\d+|policies/\d+/members|test-plans/\d+/vms') +# where a plan writes: only a root target manager chooses that; everyone else gets the folder's target +_BACKUP_DEST_KEYS = ('path_uri_base', 'smb_user', 'smb_password', 'prune_path') + + +def _clean_plan_payload(payload: dict, cid: str): + """The VM's name comes from the cluster, not the browser: it is the export prefix and the key the plan's + pruning deletes by, so a user allowed one VM could otherwise name another VM and have that VM's backups + pruned. A destination of the browser's choosing is dropped unless the user manages targets on the whole + installation (else a backup.schedule holder could send a VM's export to an SMB server of their own). + Returns an error response or None.""" + if not _access().can('backup.targets.manage'): + for k in _BACKUP_DEST_KEYS: + payload.pop(k, None) + vm = str(payload.get('vm_uuid') or '').strip() + if not vm: + payload.pop('vm_name', None) # an update of an existing plan keeps the plan's own name + return None + def find(rows): + return next((v.get('name') for v in rows if v.get('uuid') == vm), None) + name = find(_vm_index_rows(cid)) or find(_vm_index_rows(cid, fresh=True)) + if not name: + return jsonify({'error': 'that VM is not on the cluster'}), 404 + payload['vm_name'] = name + return None + + @app.route('/api/backup/status') @requires('backup.view') def backup_status(): @@ -2066,6 +2340,12 @@ def backup_proxy(sub): url, token = _backup_env() route = _backup_route(request.method, sub) g.hcm_perm = route[0] if route and route[0] else 'vm.view' + if route is not None and route[1] not in ('root', 'any'): + # a write acts on the cluster it names, never on the user's first one; a resource found by its id + # ('owner') is checked on its own cluster, so it needs no cluster in the query, but may not name a wrong one + problem = _write_cluster_problem(g.hcm_perm, need=not isinstance(route[1], tuple)) + if problem is not None: + return problem cid = _cluster_id() payload = None if request.method in ('POST', 'PUT'): @@ -2107,6 +2387,10 @@ def backup_proxy(sub): return jsonify({'error': err}), 403 if body_cid: payload['cluster_id'] = body_cid + if request.method in ('POST', 'PUT') and _PLAN_WRITE_RE.fullmatch(sub): + problem = _clean_plan_payload(payload, body_cid or cid) + if problem is not None: + return problem user = session.get('username') or ('anonymous' if not _AUTH_ENABLED else None) if sub == 'notices/mute': # who muted it is the session's user, not the body's payload['muted_by'] = user @@ -2156,6 +2440,10 @@ def gen(): return Response(raw, status=status, mimetype='application/json') if scope not in (None, 'all'): data = _narrow_backup(sub, data, scope, cid) + if any(k.encode() in raw for k in _BACKUP_NAME_KEYS): + names = access_db.nameable_usernames(_access(), session.get('username')) + if names is not None: + _hide_backup_names(data, names) return jsonify(data if sees_targets else _strip_sensitive(data)), status @@ -2284,6 +2572,12 @@ def cluster_alerts(): counts[it['severity']] += 1 items.sort(key=lambda i: (ALERT_LEVELS.index(i['severity']), i.get('since') or '', i['key'])) out[cid] = {'items': items, 'counts': counts} + if mutes: + # who muted it: not named to a reader below that person (an MSP's staff stay unnamed to a customer) + names = access_db.nameable_usernames(_access(), session.get('username')) + if names is not None: + for v in out.values(): + access_db.hide_names(v['items'], ('muted_by',), names) return jsonify({'clusters': out}) @@ -2315,6 +2609,26 @@ def cluster_alert_mute(): return jsonify({'ok': True}) +_ALERT_HISTORY_TIMEOUT_MS = 60_000 # 30 days of a busy cluster's conditions: more than the 10 s default +_ALERT_LATEST_RANGE = '1d' + + +def _alert_history_query(start: str, fields, raw_levels, tail: str) -> str: + """A condition_metrics query for the alert history. The filters InfluxDB can push down to storage come + first, as equality tests: measurement, then _field, then severity as an `or` chain. contains() is not + pushed down: with it right after the measurement, the field filter, unique() and last() ran in the Flux + engine over every field of every condition series (16 s on one real cluster, a 503 after 28 s on another).""" + flt = lambda col, values: ' or '.join(f'r["{col}"] == {json.dumps(v)}' for v in values) or 'false' # noqa: E731 + return f""" + from(bucket: "{INFLUX_BUCKET}") + |> range(start: {start}) + {_flux_cluster()} + |> filter(fn: (r) => r["_measurement"] == "condition_metrics") + |> filter(fn: (r) => {flt('_field', fields)}) + |> filter(fn: (r) => {flt('severity', raw_levels)}) + {tail}""" + + @app.route('/api/cluster-alerts/history') @requires('cluster.view') def cluster_alert_history(): @@ -2327,30 +2641,25 @@ def cluster_alert_history(): levels = {s for s in (request.args.get('severity') or '').split(',') if s in ALERT_LEVELS} or set(ALERT_LEVELS) raw_levels = [k for k, v in ALERT_SEVERITY.items() if v in levels] since_ms = int((time.time() - days * 86400) * 1000) - base = f""" - from(bucket: "{INFLUX_BUCKET}") - |> range(start: -{days}d) - {_flux_cluster()} - |> filter(fn: (r) => r["_measurement"] == "condition_metrics") - |> filter(fn: (r) => contains(value: r["severity"], set: {_flux_set(raw_levels)}))""" set_times: dict = {} clear_times: dict = {} latest: dict = {} meta: dict = {} - client = get_influx_client() + client = get_influx_client(timeout=_ALERT_HISTORY_TIMEOUT_MS) try: q = client.query_api() - for field, target in (('last_set_time', set_times), ('last_clear_time', clear_times)): - for table in q.query(org=INFLUX_ORG, query=base + f""" - |> filter(fn: (r) => r["_field"] == "{field}") - |> unique(column: "_value")"""): - for rec in table.records: - key = (rec.values.get('condition_name'), rec.values.get('node_uuid') or '') - target.setdefault(key, set()).add(int(rec.get_value() or 0)) - meta.setdefault(key, {'severity': rec.values.get('severity'), 'node_ip': rec.values.get('node_lan_ip') or ''}) - for table in q.query(org=INFLUX_ORG, query=base + """ - |> filter(fn: (r) => r["_field"] == "value" or r["_field"] == "is_ok" or r["_field"] == "last_set_time" or r["_field"] == "description") - |> last()"""): + # one query for both kinds of times (unique() works per series, and _field is part of the series) + for table in q.query(org=INFLUX_ORG, query=_alert_history_query( + f'-{days}d', ('last_set_time', 'last_clear_time'), raw_levels, '|> unique(column: "_value")')): + for rec in table.records: + key = (rec.values.get('condition_name'), rec.values.get('node_uuid') or '') + target = set_times if rec.get_field() == 'last_set_time' else clear_times + target.setdefault(key, set()).add(int(rec.get_value() or 0)) + meta.setdefault(key, {'severity': rec.values.get('severity'), 'node_ip': rec.values.get('node_lan_ip') or ''}) + # the latest point of each condition: the Collector writes every condition on every poll, so a day + # holds the latest of every one still reported (a longer range only made last() read more) + for table in q.query(org=INFLUX_ORG, query=_alert_history_query( + f'-{_ALERT_LATEST_RANGE}', ('value', 'is_ok', 'last_set_time', 'description'), raw_levels, '|> last()')): for rec in table.records: key = (rec.values.get('condition_name'), rec.values.get('node_uuid') or '') latest.setdefault(key, {})[rec.get_field()] = rec.get_value() @@ -2400,9 +2709,26 @@ def _console_binding(create: bool) -> str: return hashlib.sha256(f"{session.get('user_id') or ''}:{nonce}".encode()).hexdigest() +def _trusted_proxies() -> int: + try: + return max(0, int(os.getenv('HCM_TRUSTED_PROXIES', '0') or 0)) + except ValueError: + return 0 + + def _client_ip() -> str: - fwd = (request.headers.get('X-Forwarded-For') or '').split(',')[0].strip() - return fwd or request.headers.get('X-Real-IP') or request.remote_addr or '' + """The client's address: the connecting peer, unless HCM_TRUSTED_PROXIES (how many reverse proxies stand + in front of HCM) says which X-Forwarded-For entry a proxy of ours wrote. The leftmost entry is whatever + the client sent, so it is never believed (it would let anyone pick the address that sign-in limits count + and the audit records).""" + peer = request.remote_addr or '' + n = _trusted_proxies() + if n <= 0: + return peer + hops = [h.strip() for h in (request.headers.get('X-Forwarded-For') or '').split(',') if h.strip()] + if not hops: + return peer + return hops[-n] if len(hops) >= n else hops[0] def _console_user() -> str: @@ -2454,9 +2780,22 @@ def console_ticket(): status, raw, ctype = _console_call('POST', 'tickets', payload={ 'cluster_id': cid, 'vm_uuid': vm, 'username': _console_user(), 'binding': _console_binding(create=True), 'client_ip': _client_ip()}, timeout=30) + if status == 200: + try: + ticket = json.loads(raw.decode() or '{}').get('ticket') + except ValueError: + ticket = None + if ticket: + # which VM a ticket opens, so the websocket can re-check the right to it while the console is open + seen = dict(session.get('console_vms') or {}) + seen[hashlib.sha256(ticket.encode()).hexdigest()[:16]] = [cid, vm] + session['console_vms'] = dict(list(seen.items())[-4:]) return Response(raw, status=status, mimetype=ctype) +_CONSOLE_RECHECK_SECONDS = 120 + + @sock.route('/console/ws') @public('checks the session and the one-time ticket itself') def console_ws(ws): @@ -2472,12 +2811,27 @@ def console_ws(ws): if not binding or not ticket: ws.close(reason=4401, message='console ticket required') return - _relay_pipe(ws, ticket, binding) + target = (session.get('console_vms') or {}).get(hashlib.sha256(ticket.encode()).hexdigest()[:16]) + recheck = None + if _AUTH_ENABLED and target: + cid, vm = target + + def recheck() -> bool: + # an open console outlives the checks made when it opened: every few minutes the login must still + # be live (not disabled, sessions not ended) and the user must still hold vm.console on this VM + access_db.begin_request() + g.pop('hcm_access', None) + try: + return _login_problem() is None and _can_vm('vm.console', cid, vm) + except Exception: # noqa: BLE001 — the database is down: keep the console, check again later + return True + _relay_pipe(ws, ticket, binding, recheck=recheck) -def _relay_pipe(ws, ticket: str, binding: str) -> None: +def _relay_pipe(ws, ticket: str, binding: str, recheck=None) -> None: """Pipe a browser websocket to the console service's relay for a ticket bound to `binding`. The - ticket is checked (and consumed) there. Shared by the users' console and the guest console.""" + ticket is checked (and consumed) there. Shared by the users' console and the guest console. + recheck(): called every _CONSOLE_RECHECK_SECONDS; False closes the console.""" url = CONSOLE_API_URL.replace('http://', 'ws://', 1).replace('https://', 'wss://', 1) qs = urllib.parse.urlencode({'ticket': ticket, 'binding': binding}) try: @@ -2507,9 +2861,18 @@ def upstream_to_browser(): pump = threading.Thread(target=upstream_to_browser, daemon=True, name='console-pump') pump.start() + checked = time.monotonic() try: while True: - data = ws.receive() + data = ws.receive(timeout=30 if recheck else None) + if recheck and time.monotonic() - checked >= _CONSOLE_RECHECK_SECONDS: + checked = time.monotonic() + if not recheck(): + try: + ws.close(reason=4403, message='console access ended') + except Exception: # noqa: BLE001 + pass + break if data is None: continue up.send(data if isinstance(data, (bytes, bytearray)) else data.encode()) @@ -2574,10 +2937,10 @@ def console_proxy(sub): if sub == 'sessions' and not request.args.get('cluster'): cid = None # the audit log across every cluster the user may audit else: + problem = _write_cluster_problem(perm, need=True) + if problem is not None: + return problem cid = _cluster_id() - wanted = (request.args.get('cluster') or '').strip() - if wanted and wanted != cid and request.method not in ('GET', 'HEAD'): - return jsonify({'error': 'Access denied'}), 403 if perm != 'console.audit' and not acc.can(perm, cid): return jsonify({'error': 'Access denied'}), 403 args = [(k, v) for k, v in request.args.items(multi=True) if k != 'cluster'] @@ -2749,18 +3112,18 @@ def sentinel_summary(): @requires('cluster.view') def sentinel_forecasts(): """E1 — Latest forecast snapshots, optionally filtered by ?dimension= or ?horizon=""" + limit = _int_arg('limit', 200, 1, 1000) + horizon = _int_arg('horizon', 0, 0, 3650) if request.args.get('horizon') else None try: cid = _cluster_id() dimension = request.args.get('dimension') - horizon = request.args.get('horizon') - limit = max(1, min(int(request.args.get('limit', 200)), 1000)) where = ['cluster_id = %s', 'expires_at > NOW()'] params: list = [cid] if dimension: where.append('resource_dimension = %s'); params.append(dimension) if horizon: - where.append('forecast_horizon_days = %s'); params.append(int(horizon)) + where.append('forecast_horizon_days = %s'); params.append(horizon) params.append(limit) rows = _sentinel_query( @@ -2782,10 +3145,10 @@ def sentinel_forecasts(): @requires('cluster.view') def sentinel_rightsizing(): """E2 — Right-sizing results (C1, C2).""" + limit = _int_arg('limit', 200, 1, 1000) try: cid = _cluster_id() direction = request.args.get('direction') - limit = max(1, min(int(request.args.get('limit', 200)), 1000)) where = ['cluster_id = %s', 'expires_at > NOW()'] params: list = [cid] @@ -2812,9 +3175,9 @@ def sentinel_rightsizing(): @requires('cluster.view') def sentinel_resize(): """E2 — Concrete resize advice (C3-C6).""" + limit = _int_arg('limit', 200, 1, 1000) try: cid = _cluster_id() - limit = max(1, min(int(request.args.get('limit', 200)), 1000)) rows = _sentinel_query( '''SELECT id, vm_uuid, vm_name, node_uuid, sizing_direction, current_vcpu, recommended_vcpu, @@ -2835,9 +3198,9 @@ def sentinel_resize(): @requires('cluster.view') def sentinel_exhaustion(): """E4 — Resource exhaustion alerts, most urgent first.""" + limit = _int_arg('limit', 100, 1, 500) try: cid = _cluster_id() - limit = max(1, min(int(request.args.get('limit', 100)), 500)) rows = _sentinel_query( '''SELECT id, node_uuid, resource_dimension, days_until_exhaustion, exhaustion_date, current_usage_pct, growth_rate_per_day, @@ -2860,9 +3223,9 @@ def sentinel_exhaustion(): @requires('cluster.view') def sentinel_cluster_health(): """E3 — Cluster health score history.""" + limit = _int_arg('limit', 50, 1, 500) try: cid = _cluster_id() - limit = max(1, min(int(request.args.get('limit', 50)), 500)) rows = _sentinel_query( '''SELECT id, health_score, bottleneck_resource, growth_rates, efficiency_index, component_scores, cluster_count, @@ -3161,8 +3524,13 @@ def sentinel_put_tunables(): f'{sentinel_api_url}/api/v1/tunables?cluster={_cluster_id()}', data=payload, headers=headers, method='PUT', ) + cid = _cluster_id() with _req.urlopen(rq, timeout=10) as resp: - return jsonify(json.loads(resp.read().decode())) + out = json.loads(resp.read().decode()) + _audit('tunables.foresight', cid, node_id=_access().tree.cluster_folder.get(cid), + detail={'cluster_id': cid, 'changes': {str(k)[:80]: v for k, v in list(body.items())[:50]} + if isinstance(body, dict) else None}) + return jsonify(out) except urllib.error.HTTPError as e: body_err = e.read().decode(errors='replace') return jsonify({'error': body_err}), e.code @@ -3201,6 +3569,9 @@ def sentinel_trigger_trend_run(): # auth routes # ============================================================================= +_OTP_PENDING_SECONDS = 300 # the code must follow the password within five minutes + + @app.route('/login', methods=['GET', 'POST']) @public('the login page') def login_page(): @@ -3213,26 +3584,49 @@ def login_page(): error = None if request.method == 'POST': + client = _client_ip() if step == 'otp': - # guard: must have completed the password step first + # guard: must have completed the password step first, a few minutes ago at most pending_username = session.get('otp_pending') - if not pending_username: + pending_at = float(session.get('otp_pending_at') or 0) + if not pending_username or time.time() - pending_at > _OTP_PENDING_SECONDS: + session.pop('otp_pending', None) + session.pop('otp_pending_at', None) return redirect(url_for('login_page')) + # wrong codes are counted in the database since this password step: replaying an older cookie + # (the session lives in the client) does not give more guesses + if user_db.otp_failures_since(pending_username, pending_at) >= user_db.MAX_OTP_FAILURES: + session.pop('otp_pending', None) + session.pop('otp_pending_at', None) + return _login_render('password', 'err_otp_restart', False) code = request.form.get('otp', '').strip() if user_db.verify_otp_code(pending_username, code): u = user_db.get_by_username(pending_username) session.pop('otp_pending', None) + session.pop('otp_pending_at', None) + user_db.clear_login_failures(pending_username) dest = _after_login(session.pop('next', None)) - session['user_id'] = str(u['user_id']) - session['username'] = u['username'] - session['role'] = u['role'] + _start_session(u) + _audit('login', u['username'], detail={'ip': client, 'otp': True}, actor=u['username']) return redirect(dest) + user_db.record_login_failure(pending_username, client, 'otp') + _audit('login.otp_failed', pending_username, detail={'ip': client}, actor=pending_username) + if user_db.otp_failures_since(pending_username, pending_at) >= user_db.MAX_OTP_FAILURES: + session.pop('otp_pending', None) + session.pop('otp_pending_at', None) + return _login_render('password', 'err_otp_restart', False) error = 'err_otp' else: - found = user_db.get_by_login(request.form.get('username', '')) - username = found['username'] if found else request.form.get('username', '').strip() + typed = request.form.get('username', '') + if user_db.login_locked(typed, client): + # counted by what was typed and by address, so the answer is the same for an unknown account + _audit('login.locked', typed.strip()[:254], detail={'ip': client}, actor='anonymous') + return _login_render('password', 'err_locked', False) + found = user_db.get_by_login(typed) + username = found['username'] if found else typed.strip() password = request.form.get('password', '') - if found and user_db.verify_password(username, password): + # always one password check, also for an unknown address (against a dummy hash): same time either way + if user_db.verify_password(username, password) and found: u = found if u.get('enabled') is False: # only after a correct password: say why, so they do not retry into a lockout @@ -3242,12 +3636,16 @@ def login_page(): return _login_render('password', error, False) if u['otp_enabled']: session['otp_pending'] = username + session['otp_pending_at'] = time.time() return redirect(url_for('login_page', step='otp')) + user_db.clear_login_failures(typed) dest = _after_login(session.pop('next', None)) - session['user_id'] = str(u['user_id']) - session['username'] = u['username'] - session['role'] = u['role'] + _start_session(u) + _audit('login', u['username'], detail={'ip': client}, actor=u['username']) return redirect(dest) + user_db.record_login_failure(typed, client, 'password') + # what was typed, never the password; an unknown address is recorded as typed (that is the attempt) + _audit('login.failed', typed.strip()[:254], detail={'ip': client}, actor='anonymous') error = 'err_login' # pass otp_enabled=True only when on the OTP step (drives login.html hint text) @@ -3271,10 +3669,10 @@ def _after_login(dest): return dest if ok else url_for('index') -@app.route('/logout') +@app.route('/logout', methods=['GET', 'POST']) # POST: a form button (cross-site safe); GET: the old link @public('logging out') def logout(): - nxt = request.args.get('next') + nxt = request.values.get('next') session.clear() if _after_login(nxt) != url_for('index'): session['next'] = nxt # 'sign out and switch' on an invitation for another address @@ -3320,10 +3718,21 @@ def api_me_community_ack(): return jsonify({'ok': True, 'dev_mode': False}) -@app.route('/api/users/me/otp/setup', methods=['GET']) +@app.route('/api/users/me/otp/setup', methods=['GET', 'POST']) @requires(None) def api_otp_setup(): + """The secret to enrol an authenticator: POST {"password": }. Never once two-factor is + on (the secret would let whoever holds the session make codes), and never without the password (a stolen + session could otherwise enrol its own authenticator and lock the person out).""" username = session.get('username', 'dev') + if _AUTH_ENABLED: + u = user_db.get_by_username(username) + if u and u.get('otp_enabled'): + return jsonify({'error': 'two-factor authentication is already on; turn it off first to set it up again'}), 409 + data = (request.get_json(silent=True) or {}) if request.method == 'POST' else {} + if not user_db.verify_password(username, str(data.get('password') or '')): + return jsonify({'error': 'enter your current password to set up two-factor authentication', + 'password_required': True}), 403 try: return jsonify(user_db.build_otp_setup(username)) except Exception as e: @@ -3334,11 +3743,16 @@ def api_otp_setup(): @requires(None) def api_otp_enable(): username = session.get('username', 'dev') - data = request.get_json(force=True) or {} + data = request.get_json(silent=True) or {} code = (data.get('code') or '').strip() if not code: return jsonify({'error': 'code is required'}), 400 if user_db.enable_otp(username, code): + _audit('user.otp_enabled', username, actor=username) + if _AUTH_ENABLED: + gen = user_db.bump_session_gen(username) # other sessions signed in without the code end + if gen is not None: + session['gen'] = gen return jsonify({'ok': True}) return jsonify({'error': 'Invalid code — check your authenticator app and try again'}), 400 @@ -3347,14 +3761,19 @@ def api_otp_enable(): @requires(None) def api_otp_disable(): username = session.get('username', 'dev') - data = request.get_json(force=True) or {} + data = request.get_json(silent=True) or {} if _AUTH_ENABLED and not user_db.verify_password(username, data.get('password', '')): return jsonify({'error': 'Incorrect password'}), 403 try: user_db.disable_otp(username) - return jsonify({'ok': True}) except Exception as e: return jsonify({'error': str(e)}), 500 + _audit('user.otp_disabled', username, actor=username) + if _AUTH_ENABLED: + gen = user_db.bump_session_gen(username) # every other session of the account ends + if gen is not None: + session['gen'] = gen + return jsonify({'ok': True}) # ============================================================================= @@ -3364,6 +3783,7 @@ def api_otp_disable(): _REPO_PATH = os.getenv('SC_REPO_PATH', '/repo') _UPDATE_FILE = '/tmp/hcm_update.json' _UPDATE_FILE_LOCK = threading.Lock() +_APPLY_MAX_SECONDS = 2 * 3600 # an apply still "in progress" after this was interrupted def _read_update_file(): @@ -3374,12 +3794,74 @@ def _read_update_file(): return {} -def _write_update_patch(patch): +@contextmanager +def _update_lock(): + """The updater state is one file shared by four gunicorn workers: a thread lock within the worker and an + flock across them, so a read-modify-write (and Apply's check-and-set) is never interleaved.""" + import fcntl with _UPDATE_FILE_LOCK: + with open(_UPDATE_FILE + '.lock', 'w') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock, fcntl.LOCK_UN) + + +def _store_update_file(state: dict) -> None: + """Write through a temporary file and os.replace: a reader never sees a half-written file.""" + tmp = f'{_UPDATE_FILE}.{os.getpid()}.{threading.get_ident()}.tmp' + with open(tmp, 'w') as f: + json.dump(state, f) + os.replace(tmp, _UPDATE_FILE) + + +def _write_update_patch(patch): + with _update_lock(): state = _read_update_file() state.update(patch) - with open(_UPDATE_FILE, 'w') as f: - json.dump(state, f) + _store_update_file(state) + + +def _container_marker() -> str: + """Something that changes when this container starts again: PID 1's start time (field 22 of /proc/1/stat).""" + try: + with open('/proc/1/stat') as f: + return f.read().rsplit(')', 1)[1].split()[19] + except (OSError, IndexError): + return '' + + +def _apply_is_stale(state: dict) -> bool: + """An apply marked in progress whose thread cannot be running any more: started in an earlier life of this + container (a restart during the build), by a worker that is gone, or longer ago than any apply takes.""" + if not state.get('apply_in_progress'): + return False + if state.get('apply_marker') != _container_marker(): + return True + pid = state.get('apply_pid') + if pid: + try: + os.kill(int(pid), 0) + except (OSError, ValueError): + return True + return time.time() - float(state.get('apply_started') or 0) > _APPLY_MAX_SECONDS + + +def _clear_stale_apply() -> None: + try: + with _update_lock(): + state = _read_update_file() + if _apply_is_stale(state): + state['apply_in_progress'] = False + state.setdefault('apply_log', []).append('The previous apply was interrupted (the dashboard restarted); ' + 'it can be applied again.') + _store_update_file(state) + except OSError as exc: + app.logger.warning('updater state not checked: %s', exc) + + +_clear_stale_apply() def _git(*args, timeout=10): @@ -3399,14 +3881,23 @@ def _git(*args, timeout=10): def restart_command(fallback=_APP_SERVICES) -> str: - """Shell command the restart container runs: recreate every service of the compose file that was - just pulled, except the databases. The list comes from that new file, not from this (old) code: - an updater from 1.1.x had a fixed list without `console` and never started 1.2.0's new service. - The fixed list is the fallback when the file cannot be read.""" + """Shell command the restart container runs: recreate the services of the compose file that was just + pulled, except the databases. The list comes from that new file, not from this (old) code: an updater + from 1.1.x had a fixed list without `console` and never started 1.2.0's new service. The fixed list is + the fallback when the file cannot be read. + + Of those, only the ones running now and the ones that have no container yet (new in this release): a + service the administrator stopped stays stopped (the manual says `docker compose stop balancer`; starting + it again with DRY_RUN false would resume migrating VMs).""" skip = '|'.join(_DB_SERVICES) return ("S=$(docker-compose config --services 2>/dev/null | grep -vxE '" + skip + "' | tr '\\n' ' '); " "[ -n \"$S\" ] || S='" + ' '.join(fallback) + "'; " - "exec docker-compose up -d --no-deps $S") + "R=\" $(docker-compose ps --services --filter status=running 2>/dev/null | tr '\\n' ' ') \"; " + "A=\" $(docker-compose ps -a --services 2>/dev/null | tr '\\n' ' ') \"; " + "U=''; for s in $S; do case \"$R\" in *\" $s \"*) U=\"$U $s\";; " + "*) case \"$A\" in *\" $s \"*) ;; *) U=\"$U $s\";; esac;; esac; done; " + "[ -n \"$U\" ] || exit 0; " + "exec docker-compose up -d --no-deps $U") # Services added after 1.1.x. A stack updated by a 1.1.x dashboard has their images (the update builds @@ -3444,9 +3935,11 @@ def _self_heal_services(delay: float = 30) -> None: host_repo = os.getenv('SC_HOST_REPO_PATH', _REPO_PATH) # the same way as the updater: a helper container with the host's path of the checkout, which the # Docker daemon needs for build contexts and bind mounts + # no --env-file: docker run parses .env differently from Compose (quotes, $$); Compose in the helper + # reads /repo/.env itself r = subprocess.run(['docker', 'run', '-d', '--rm', '--name', 'hcm-self-heal', '-v', '/var/run/docker.sock:/var/run/docker.sock', '-v', f'{host_repo}:/repo', - '--env-file', f'{_REPO_PATH}/.env', '-w', '/repo', f'{project}-dashboard', + '-w', '/repo', f'{project}-dashboard', 'docker-compose', 'up', '-d', '--no-deps', '--build', *missing], capture_output=True, text=True, timeout=60) if r.returncode != 0: @@ -3492,7 +3985,7 @@ def _restore_ownership(log=None) -> None: def _read_version_file() -> str: - """Return the project version from /VERSION, or '' if unreadable.""" + """Return the version of the checkout (/VERSION), or '' if unreadable.""" try: with open(os.path.join(_REPO_PATH, 'VERSION')) as f: return f.read().strip() @@ -3500,6 +3993,23 @@ def _read_version_file() -> str: return '' +def _image_version() -> str: + """The version this dashboard image was built from (VERSION copied in by the Dockerfile), or '' for an + image from before 1.8.1. This, not the checkout, is what runs: a checkout moved to a release whose build + failed (or was never built) showed the new number for a day while the old containers ran.""" + try: + with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'VERSION')) as f: + return f.read().strip() + except OSError: + return '' + + +def _versions() -> tuple[str, str]: + """(running, checkout): the image's version, else the checkout's; and the checkout's.""" + checkout = _read_version_file() + return (_image_version() or checkout), checkout + + def _latest_remote_tag() -> str: """Return the highest semver-like tag known to git, or '' if none. @@ -3518,12 +4028,13 @@ def _changelog_between(local_tag: str, remote_tag: str) -> list[str]: def _check_for_update(): - # the running version comes from the local VERSION file and must be published even - # when the remote check fails, so the footer always shows what is installed - current_version = _read_version_file() + # the running version is the image's and must be published even when the remote check fails, so the + # footer always shows what is installed (not what the checkout says) + current_version, checkout_version = _versions() _write_update_patch({ 'current_version': current_version or None, 'current_label': f'v{current_version}' if current_version else None, + 'checkout_version': checkout_version or None, }) try: r = subprocess.run( @@ -3546,15 +4057,23 @@ def _check_for_update(): local_tag = f'v{current_version}' if current_version else '' update_available = is_newer(remote_version, current_version) + # the checkout is ahead of what runs (an apply whose build or restart failed, or a manual git pull + # without a rebuild): Apply builds and restarts it + rebuild = is_newer(checkout_version, current_version) + if rebuild and not update_available: + update_available, remote_version = True, checkout_version + remote_tag = remote_tag or f'v{checkout_version}' changelog = _changelog_between(local_tag, remote_tag) if update_available else [] # applying moves the checkout to exactly that tag: say now if it would refuse (another branch, # local commits, an inconsistent release) instead of after the administrator presses Apply - blocked = resolve_apply(_REPO_PATH, remote_tag)['error'] if update_available else None + blocked = resolve_apply(_REPO_PATH, _latest_remote_tag())['error'] if update_available else None _write_update_patch({ 'update_available': update_available, + 'rebuild_needed': rebuild, 'current_version': current_version or None, + 'checkout_version': checkout_version or None, 'remote_version': remote_version or None, # rendered by the existing frontend; keep populated for back-compat 'current_label': f'v{current_version}' if current_version else None, @@ -3629,11 +4148,15 @@ def _apply_migrations_on_startup(): def _do_apply_update(): def log(msg): ts = datetime.now(timezone.utc).strftime('%H:%M:%S') - with _UPDATE_FILE_LOCK: + with _update_lock(): state = _read_update_file() state.setdefault('apply_log', []).append(f'[{ts}] {msg}') - with open(_UPDATE_FILE, 'w') as f: - json.dump(state, f) + _store_update_file(state) + + def failed(why: str): + # the old containers still run: keep the old version on show and Apply on offer + log(why) + _write_update_patch({'apply_in_progress': False, 'apply_failed': why[:500]}) try: # exactly the advertised release: fetch the tags, decide before touching anything, then move the @@ -3678,24 +4201,27 @@ def log(msg): capture_output=True, text=True, timeout=30, ) if pop.returncode != 0: - log(f'Warning: stash pop had conflicts — manual resolve needed on server.') - log('Run: git -C /path/to/repo stash pop') + # building now would bake conflict markers into the images + _restore_ownership(log) + failed(f"Your local changes conflict with {plan['tag']}: nothing was built or restarted. On the server, " + 'resolve them (git status; the changes are kept in git stash list), then apply again.') + return _restore_ownership(log) - # what is installed now: the dialog must not keep showing the old version until the restart now = _read_version_file() - _write_update_patch({'current_version': now or None, 'current_label': f'v{now}' if now else None, - 'update_available': False, 'apply_blocked': None, 'changelog': []}) log('Building new images (no downtime yet)...') - r = subprocess.run( - ['docker-compose', 'build'], - capture_output=True, text=True, timeout=600, - cwd=_REPO_PATH, - ) + try: + r = subprocess.run( + ['docker-compose', 'build'], + capture_output=True, text=True, timeout=600, + cwd=_REPO_PATH, + ) + except subprocess.TimeoutExpired: + failed('docker-compose build did not finish within 10 minutes; the running version is unchanged. Apply again.') + return if r.returncode != 0: - log(f'docker-compose build failed: {(r.stderr or r.stdout).strip()}') - _write_update_patch({'apply_in_progress': False}) + failed(f'docker-compose build failed: {(r.stderr or r.stdout).strip()[-2000:]}') return log('Applying pending database migrations...') @@ -3710,12 +4236,10 @@ def log(msg): log('Schema already up-to-date — no migrations to apply.') except Exception as exc: log(f'Migration step failed: {exc}') - log('Aborting recreate — fix the migration error and re-run Apply Update.') - _write_update_patch({'apply_in_progress': False}) + failed('Aborting recreate — fix the migration error and re-run Apply Update.') return log('Build done. Spawning restart container...') - _write_update_patch({'update_available': False}) project = os.getenv('COMPOSE_PROJECT_NAME', 'drsproject') # _REPO_PATH is /repo inside the container, but the Docker daemon needs # the real host-side path for volume mounts @@ -3723,13 +4247,14 @@ def log(msg): # remove stale updater container if a previous run left one behind subprocess.run(['docker', 'rm', '-f', 'hcm-auto-updater'], capture_output=True) + # no --env-file: docker run parses .env differently from Compose (quotes, $$); Compose in the helper + # reads /repo/.env itself r = subprocess.run( [ 'docker', 'run', '-d', '--rm', '--name', 'hcm-auto-updater', '-v', '/var/run/docker.sock:/var/run/docker.sock', '-v', f'{host_repo}:/repo', - '--env-file', f'{_REPO_PATH}/.env', '-w', '/repo', f'{project}-dashboard', 'sh', '-c', restart_command(), @@ -3737,14 +4262,15 @@ def log(msg): capture_output=True, text=True, timeout=30, ) if r.returncode != 0: - log(f'docker run failed: {(r.stderr or r.stdout).strip()}') - _write_update_patch({'apply_in_progress': False}) + failed(f'docker run failed: {(r.stderr or r.stdout).strip()}') return log(f'Restart container spawned ({r.stdout.strip()[:12]}); the databases keep running. Page will reload shortly.') - _write_update_patch({'apply_in_progress': False}) + # only now is the new version on its way in: say so (until the restart replaces this container) + _write_update_patch({'apply_in_progress': False, 'apply_failed': None, 'update_available': False, + 'current_version': now or None, 'current_label': f'v{now}' if now else None, + 'apply_blocked': None, 'changelog': []}) except Exception as exc: - log(f'Error: {exc}') - _write_update_patch({'apply_in_progress': False}) + failed(f'Error: {exc}') @app.route('/api/update/status') @@ -3761,9 +4287,12 @@ def api_update_status(): 'repo_url': state.get('repo_url'), 'last_checked': state.get('last_checked'), 'error': state.get('error'), - 'apply_in_progress': state.get('apply_in_progress', False), + 'apply_in_progress': bool(state.get('apply_in_progress')) and not _apply_is_stale(state), 'apply_log': state.get('apply_log', []), 'apply_blocked': state.get('apply_blocked'), + 'apply_failed': state.get('apply_failed'), + 'checkout_version': state.get('checkout_version'), + 'rebuild_needed': state.get('rebuild_needed', False), }) @@ -3777,10 +4306,15 @@ def api_update_check(): @app.route('/api/update/apply', methods=['POST']) @requires('install.manage', 'root') def api_update_apply(): - state = _read_update_file() - if state.get('apply_in_progress'): - return jsonify({'error': 'Update already in progress'}), 409 - _write_update_patch({'apply_in_progress': True, 'apply_log': []}) + with _update_lock(): # check-and-set: two clicks (or two workers) start one apply + state = _read_update_file() + if state.get('apply_in_progress') and not _apply_is_stale(state): + return jsonify({'error': 'Update already in progress'}), 409 + state.update({'apply_in_progress': True, 'apply_log': [], 'apply_failed': None, 'apply_pid': os.getpid(), + 'apply_marker': _container_marker(), 'apply_started': time.time()}) + _store_update_file(state) + _audit('install.update_apply', state.get('remote_label') or 'update', + detail={'from': state.get('current_version'), 'to': state.get('remote_version')}) threading.Thread(target=_do_apply_update, daemon=True).start() return jsonify({'ok': True}) diff --git a/dashboard/cluster_registry.py b/dashboard/cluster_registry.py index 2157c49..8650f82 100644 --- a/dashboard/cluster_registry.py +++ b/dashboard/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -162,9 +177,11 @@ def _row_to_cluster(r: dict) -> Cluster: # --------------------------------------------------------------------------- def list_all(include_template: bool = False) -> list[Cluster]: - sql = f'SELECT {_COLUMNS} {_FROM}' + """The registered clusters. A removed one (Remove keeps its row, renamed '(removed ...)', so history stays + valid) is not registered any more and is left out: it showed up with an Enable button.""" + sql = f'SELECT {_COLUMNS} {_FROM} WHERE c.is_active = TRUE' if not include_template: - sql += ' WHERE c.is_template = FALSE' + sql += ' AND c.is_template = FALSE' sql += ' ORDER BY c.is_template DESC, lower(c.cluster_name)' conn = _connect() try: @@ -238,7 +255,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -270,10 +290,11 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = username: Optional[str] = None, password: Optional[str] = None, verify_tls: Optional[bool] = None, colour: Optional[str] = None, enabled: Optional[bool] = None, folder_id: Optional[str] = ..., api_version: Optional[str] = None, - timezone: Optional[str] = None) -> None: + timezone: Optional[str] = None) -> Optional[int]: """Update the given fields; password is re-encrypted only when provided (non-empty). folder_id: a folder uuid to move the cluster, None to unfile it, omitted to leave it. - timezone: an IANA name to override what the cluster reports, '' to follow the cluster again.""" + timezone: an IANA name to override what the cluster reports, '' to follow the cluster again. + Returns the number of rows changed (0: no such registered cluster), None when nothing was asked.""" sets, params = [], [] if timezone is not None: tz = timezone.strip() @@ -287,8 +308,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,13 +322,20 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: if api_version not in API_VERSIONS: raise ValueError("api_version must be auto, v1 or v2") sets.append('api_version = %s'); params.append(api_version) + if (host is not None or username is not None) and not password: + # the stored password follows the entry: pointed at another address (or user) it would be sent there by + # the next connection test and by every service's next login. Whoever moves it supplies the password. + current = get(cluster_id) + if current and ((host is not None and normalize_host(host) != current.host) + or (username is not None and username.strip() != current.username)): + raise ValueError('changing the address or the user name needs the password in the same request') if not sets: return sets.append('updated_at = NOW()') @@ -314,11 +346,15 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = conn = _connect() try: with conn.cursor() as cur: + # a removed cluster is not changed (enabling one, with no password left, made every service try an + # empty-password login each poll) cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} ' - f'WHERE cluster_id = %s AND is_template = FALSE', params) + f'WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE', params) + changed = cur.rowcount conn.commit() finally: conn.close() + return changed def delete(cluster_id: str, purge: bool = False) -> None: @@ -335,20 +371,26 @@ def delete(cluster_id: str, purge: bool = False) -> None: cur.execute('DELETE FROM config.module_toggles WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.branding WHERE cluster_id = %s', (cluster_id,)) if purge: + # children before the rows they reference: webhook deliveries and the action log point at + # recommendation events, resize advice at right-sizing rows + events = 'SELECT id FROM audit.recommendation_events WHERE cluster_id = %s' + for table in ('audit.webhook_deliveries', 'audit.action_log'): + cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s OR recommendation_event_id IN ({events})', + (cluster_id, cluster_id)) for table in ('recommendations.resize_recommendations', 'recommendations.right_sizing', 'recommendations.forecast_snapshots', 'recommendations.resource_exhaustion', - 'recommendations.cluster_health_scores', 'audit.recommendation_events', - 'audit.action_log', 'audit.webhook_deliveries'): + 'recommendations.cluster_health_scores', 'audit.recommendation_events'): cur.execute(f'DELETE FROM {table} WHERE cluster_id = %s', (cluster_id,)) cur.execute('DELETE FROM config.clusters WHERE cluster_id = %s AND is_template = FALSE', (cluster_id,)) else: - # keep the row so FK-bound history stays valid, but take it out of service + # keep the row so FK-bound history stays valid, but take it out of service (once: removing it + # again would append a second '(removed ...)') cur.execute('''UPDATE config.clusters SET enabled = FALSE, is_active = FALSE, hc_password_enc = NULL, cluster_name = cluster_name || ' (removed ' || to_char(NOW(), 'YYYY-MM-DD HH24:MI') || ')', updated_at = NOW() - WHERE cluster_id = %s AND is_template = FALSE''', (cluster_id,)) + WHERE cluster_id = %s AND is_template = FALSE AND is_active = TRUE''', (cluster_id,)) conn.commit() finally: conn.close() @@ -413,15 +455,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +579,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +589,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +599,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +639,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +719,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +738,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +758,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +785,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +795,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- @@ -836,7 +890,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -851,7 +905,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/dashboard/config_db.py b/dashboard/config_db.py index 31909ef..6d7e801 100644 --- a/dashboard/config_db.py +++ b/dashboard/config_db.py @@ -15,8 +15,9 @@ Connection: PG_HOST / PG_PORT / PG_DB / PG_USER / PG_PASSWORD env vars. Graceful degradation: if PostgreSQL is unreachable, all reads fall back to -the env var value for that key (or the hardcoded default). Writes are -silently dropped with a warning log. The service continues operating normally. +the env var value for that key (or the hardcoded default), and a stored value +that cannot be cast falls back for that key only. save() drops a write with a +warning; save_many() (the settings API) raises so the caller can report it. On first run, values are seeded from environment variables (falling back to hardcoded defaults). After that, env vars are ignored for keys the user has @@ -74,14 +75,48 @@ 'STALE_SECONDS': ('SC_DASHBOARD_STALE_SECONDS', 120, 'int'), } +# key → (min, max) a stored value must lie within; the same ranges as the settings sliders +# (CTRL_GROUPS in dashboard/static/index.html), checked again by validate() on every write +RANGES = { + 'VERBOSITY': (0, 3), + 'AVG_WINDOW_MINUTES': (1, 30), + 'SAMPLE_INTERVAL_SECONDS': (10, 300), + 'RAM_LIMIT_PERCENT': (50, 100), + 'RAM_UPPER_THRESHOLD_PERCENT': (10, 100), + 'CPU_UPPER_THRESHOLD_PERCENT': (10, 100), + 'MAX_VCPU_RATIO': (0.5, 8.0), + 'VM_MOVE_COOLDOWN_MINUTES': (0, 120), + 'MIGRATION_COOLDOWN_MINUTES': (0, 60), + 'CPU_TARGET_TOLERANCE_PERCENT': (1, 20), + 'PREDICTIVE_INTERVAL_SECONDS': (3600, 86400), + 'PREDICTIVE_LEAD_TIME_HOURS': (1, 24), + 'PREDICTIVE_THRESHOLD': (50, 100), + 'PREDICTIVE_MIN_HISTORY_HOURS': (24, 720), + 'PREDICTIVE_LOOKBACK_DAYS': (7, 365), + 'PREDICTIVE_MAX_WORKERS': (1, 16), + 'PREDICTIVE_RESERVATION_MINUTES': (0, 120), + 'POLL_INTERVAL': (10, 120), + 'SLOW_POLL_INTERVAL': (60, 3600), + 'INFLUX_WRITE_RETRIES': (1, 10), + 'INFLUX_RETRY_DELAY': (1, 30), + 'STALE_SECONDS': (30, 600), +} + +_TRUE, _FALSE = ('true', '1', 'yes', 'y'), ('false', '0', 'no', 'n', '') + # --------------------------------------------------------------------------- # type helpers # --------------------------------------------------------------------------- def _cast(value: str, type_hint: str) -> Any: + """Stored text → Python value. Raises ValueError for text that is not a value of the type + (an emptied number field once stored 'None'; a bool reading 'None' was silently false).""" if type_hint == 'bool': - return str(value).lower() in ('true', '1', 'yes', 'y') + v = str(value).strip().lower() + if v in _TRUE or v in _FALSE: + return v in _TRUE + raise ValueError(f'not a boolean: {value!r}') if type_hint == 'int': return int(float(value)) # float() first handles "30.0" edge case if type_hint == 'float': @@ -95,10 +130,47 @@ def _serialize(value: Any, type_hint: str) -> str: if type_hint == 'list': return ','.join(str(v) for v in value) if isinstance(value, list) else str(value) if type_hint == 'bool': + if isinstance(value, str): # the string 'false' is truthy: it was stored as true + value = _cast(value, 'bool') return 'true' if value else 'false' return str(value) +def validate(key: str, value: Any) -> Any: + """The typed value `value` stands for, or ValueError: unknown key, null, not castable to the + key's type, not a finite number, or outside RANGES. Run on every value before it is stored, + since one value no reader can cast used to cost the whole cluster its settings.""" + if key not in TUNABLES: + raise ValueError(f'unknown setting {key}') + if value is None: + raise ValueError(f'{key}: a value is required') + type_hint = TUNABLES[key][2] + if type_hint in ('int', 'float') and (isinstance(value, bool) or (isinstance(value, str) and not value.strip())): + raise ValueError(f'{key}: a number is required') + if type_hint == 'list' and not isinstance(value, (str, list)): + raise ValueError(f'{key}: a comma-separated list is required') + try: + typed = _cast(_serialize(value, type_hint), type_hint) + except (TypeError, ValueError, OverflowError): + raise ValueError(f'{key}: {value!r} is not a valid {type_hint}') from None + if type_hint in ('int', 'float'): + if typed != typed or typed in (float('inf'), float('-inf')): + raise ValueError(f'{key}: {value!r} is not a valid {type_hint}') + lo, hi = RANGES.get(key, (None, None)) + if (lo is not None and typed < lo) or (hi is not None and typed > hi): + raise ValueError(f'{key}: {typed} is outside {lo}..{hi}') + return typed + + +def _read(key: str, raw: str, type_hint: str) -> Any: + """One stored row, cast; a value that cannot be read falls back for that key only.""" + try: + return _cast(raw, type_hint) + except (TypeError, ValueError, OverflowError): + logger.warning('config_db: stored value %r for %s is not a valid %s, using the default', raw, key, type_hint) + return _env_fallback(key) + + # --------------------------------------------------------------------------- # internal helpers # --------------------------------------------------------------------------- @@ -121,7 +193,10 @@ def _env_fallback(key: str) -> Any: return None env_var, default, type_hint = entry raw = os.getenv(env_var) - return _cast(raw, type_hint) if raw else default + try: + return _cast(raw, type_hint) if raw else default + except (TypeError, ValueError): + return default # --------------------------------------------------------------------------- @@ -144,8 +219,7 @@ def seed_from_env() -> None: try: with conn.cursor() as cur: for key, (env_var, default, type_hint) in TUNABLES.items(): - raw_env = os.getenv(env_var) or None - value = _cast(raw_env, type_hint) if raw_env is not None else default + value = _env_fallback(key) cur.execute( '''INSERT INTO config.tunables (cluster_id, key, value, type) VALUES (%s, %s, %s, %s) @@ -196,7 +270,7 @@ def get(key: str, cluster_id: str = TEMPLATE_CLUSTER_ID) -> Any: conn.close() if row is None: return _env_fallback(key) - return _cast(row[0], row[1]) + return _read(key, row[0], row[1]) except Exception as exc: logger.warning('config_db: PostgreSQL unavailable for get(%s), using env fallback: %s', key, exc) return _env_fallback(key) @@ -216,7 +290,7 @@ def get_all(cluster_id: str = TEMPLATE_CLUSTER_ID) -> dict: rows = cur.fetchall() finally: conn.close() - return {r[0]: _cast(r[1], r[2]) for r in rows} + return {r[0]: _read(r[0], r[1], r[2]) for r in rows} except Exception as exc: logger.warning('config_db: PostgreSQL unavailable for get_all(), using env fallback: %s', exc) return {k: _env_fallback(k) for k in TUNABLES} @@ -247,28 +321,29 @@ def save(key: str, value: Any, cluster_id: str = TEMPLATE_CLUSTER_ID) -> None: def save_many(updates: dict, cluster_id: str = TEMPLATE_CLUSTER_ID) -> None: - """Upsert multiple tunables in one transaction. Unknown keys are silently skipped.""" + """Upsert multiple tunables in one transaction. Unknown keys are skipped; callers validate() + first. Raises when the write fails, so nobody answers 'saved' for a change that was dropped.""" with _lock: + conn = _connect() try: - conn = _connect() - try: - with conn.cursor() as cur: - for key, value in updates.items(): - if key not in TUNABLES: - continue - _, _, type_hint = TUNABLES[key] - cur.execute( - '''INSERT INTO config.tunables (cluster_id, key, value, type, updated_at) - VALUES (%s, %s, %s, %s, NOW()) - ON CONFLICT (cluster_id, key) DO UPDATE - SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at''', - (cluster_id, key, _serialize(value, type_hint), type_hint), - ) - conn.commit() - finally: - conn.close() - except Exception as exc: - logger.warning('config_db: PostgreSQL unavailable for save_many(), changes dropped: %s', exc) + with conn.cursor() as cur: + for key, value in updates.items(): + if key not in TUNABLES: + continue + _, _, type_hint = TUNABLES[key] + cur.execute( + '''INSERT INTO config.tunables (cluster_id, key, value, type, updated_at) + VALUES (%s, %s, %s, %s, NOW()) + ON CONFLICT (cluster_id, key) DO UPDATE + SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at''', + (cluster_id, key, _serialize(value, type_hint), type_hint), + ) + conn.commit() + except Exception: + logger.warning('config_db: save_many() for %s failed, nothing stored', cluster_id, exc_info=True) + raise + finally: + conn.close() def get_with_meta(cluster_id: str = TEMPLATE_CLUSTER_ID) -> list: @@ -289,7 +364,7 @@ def get_with_meta(cluster_id: str = TEMPLATE_CLUSTER_ID) -> list: finally: conn.close() return [ - {'key': r[0], 'value': _cast(r[1], r[2]), 'type': r[2], 'updated_at': str(r[3])} + {'key': r[0], 'value': _read(r[0], r[1], r[2]), 'type': r[2], 'updated_at': str(r[3])} for r in rows ] except Exception as exc: diff --git a/dashboard/constraints.txt b/dashboard/constraints.txt new file mode 100644 index 0000000..6dab584 --- /dev/null +++ b/dashboard/constraints.txt @@ -0,0 +1,37 @@ +# Every package of the working dashboard image, transitive ones included (pip freeze, 2026-11-22, release 1.8.1). +# requirements.txt says what the service needs; this file keeps a rebuild months from now on the +# versions it was tested with (the Dockerfile installs with -c). Regenerate after changing requirements: +# docker run --rm --entrypoint pip freeze +blinker==1.9.0 +certifi==2026.10.23 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.1 +cryptography==42.0.8 +Flask==3.1.3 +flask-cors==6.0.5 +flask-sock==0.7.0 +gunicorn==26.2.0 +h11==0.16.0 +idna==3.20 +influxdb-client==1.50.0 +itsdangerous==2.2.0 +Jinja2==3.1.6 +Markdown==3.8.2 +MarkupSafe==3.0.4 +packaging==26.3 +pillow==13.0.0 +psycopg2-binary==2.9.13 +pycparser==3.12 +PyOTP==2.10.0 +python-dateutil==4.0.0 +qrcode==8.2 +reactivex==6.1.0 +reportlab==5.0.1 +requests==2.34.2 +simple-websocket==1.1.0 +typing_extensions==4.16.0 +tzdata==2025.2 +urllib3==2.8.0 +Werkzeug==3.1.9 +wsproto==1.3.2 diff --git a/dashboard/guest_api.py b/dashboard/guest_api.py index 9b5c807..ffe0e5e 100644 --- a/dashboard/guest_api.py +++ b/dashboard/guest_api.py @@ -146,6 +146,28 @@ def update(gid: int, **fields) -> None: finally: conn.close() + def counter(sql: str, params) -> int | None: + """One atomic UPDATE ... RETURNING on a grant's counter (four workers: never read, add, write back).""" + conn = db() + try: + with conn.cursor() as cur: + cur.execute(sql, params) + row = cur.fetchone() + conn.commit() + finally: + conn.close() + return int(list(row.values())[0]) if row else None + + def count_failed_code(gid: int) -> int: + return counter("""UPDATE console.guest_grants SET failed_codes = COALESCE(failed_codes, 0) + 1, + status = CASE WHEN COALESCE(failed_codes, 0) + 1 >= %s THEN 'locked' ELSE status END + WHERE id = %s RETURNING failed_codes""", (MAX_FAILED, gid)) or MAX_FAILED + + def claim_session(gid: int) -> int | None: + """The next session of the grant, or None when every one is used (also by a request a moment earlier).""" + return counter("""UPDATE console.guest_grants SET sessions_used = sessions_used + 1 + WHERE id = %s AND sessions_used < max_sessions RETURNING sessions_used""", (gid,)) + def label(g) -> str: return f"{g['guest_name']}{' (' + g['guest_company'] + ')' if g.get('guest_company') else ''} on {g.get('vm_name') or g['vm_uuid']}" @@ -183,6 +205,13 @@ def fields_from(b: dict) -> dict: name = str(b.get('guest_name') or '').strip() if not name or len(name) > 120: raise AccessError("the guest's name is required (at most 120 characters)") + company = str(b.get('guest_company') or '').strip() + if len(company) > 120: + raise AccessError("the guest's company is at most 120 characters") + # name and company go into the approvers' mail; the label onto the guest's page + access_db.no_control(name, "the guest's name") + access_db.no_control(company, "the guest's company") + access_db.no_control(b.get('label'), 'the label') vf = _parse_time(b.get('valid_from') or _now().isoformat(), 'valid from') vu = _parse_time(b.get('valid_until'), 'valid until') if vu <= vf: @@ -203,7 +232,7 @@ def fields_from(b: dict) -> dict: raise AccessError('that VM is not on the cluster', 404) return {'cluster_id': cid, 'vm_uuid': vm, 'vm_name': vm_name, 'label': (str(b.get('label') or '').strip() or 'Console')[:60], - 'guest_name': name, 'guest_company': (str(b.get('guest_company') or '').strip() or None), + 'guest_name': name, 'guest_company': company or None, 'reason': (str(b.get('reason') or '').strip()[:500] or None), 'valid_from': vf, 'valid_until': vu, 'max_minutes': max_minutes, 'max_sessions': max_sessions, 'allow_open_session': bool(b.get('allow_open_session'))} @@ -331,6 +360,11 @@ def notify_granters(gid: int, f: dict, lang: str | None) -> bool: Sent in the background; True when at least one mail is on its way.""" if not mailer.configured(): return False + base = mailer.link_base() + if not base: + # never the requester's Host header: the approvers would get a genuine mail with a link of their choosing + app.logger.warning('guest request %s: no mail to the approvers: %s', gid, mailer.LINK_ADDRESS_MISSING) + return False try: tree = h.access().tree tags = next((v.get('tags') or [] for v in h.vm_index_rows(f['cluster_id']) if v.get('uuid') == f['vm_uuid']), []) @@ -347,7 +381,7 @@ def notify_granters(gid: int, f: dict, lang: str | None) -> bool: cluster = next((c.name for c in h.clusters() if str(c.cluster_id) == f['cluster_id']), '') values = {'vm': f['vm_name'], 'cluster': cluster or '-', 'guest': f['guest_name'] + (f" ({f['guest_company']})" if f.get('guest_company') else ''), - 'link': f'{mailer.link_base(request.host_url)}/guest-requests/{gid}'} + 'link': f'{base}/guest-requests/{gid}'} by = actor() def send(): @@ -539,8 +573,7 @@ def guest_entry(token): samesite='Strict', secure=https(), max_age=max(60, int((g['valid_until'] - _now()).total_seconds()))) return _harden(resp) - failed = (g['failed_codes'] or 0) + 1 - update(g['id'], failed_codes=failed, status='locked' if failed >= MAX_FAILED else g['status']) + failed = count_failed_code(g['id']) audit('guest.code_failed', label(g), g['cluster_id'], {'ip': h.client_ip(), 'attempt': failed}, who=f"guest:{g['guest_name']}") if failed >= MAX_FAILED: @@ -592,8 +625,10 @@ def guest_ticket(token): if status != 200: return jsonify({'error': 'the console cannot be opened right now'}), 502 d = json.loads(raw.decode() or '{}') - update(g['id'], sessions_used=g['sessions_used'] + 1) - audit('guest.session', label(g), g['cluster_id'], {'ip': h.client_ip(), 'session': g['sessions_used'] + 1}, who=who) + used = claim_session(g['id']) + if used is None: # two tickets asked for at once: the ticket just issued is not handed out + return jsonify({'error': 'every session of this access has been used'}), 403 + audit('guest.session', label(g), g['cluster_id'], {'ip': h.client_ip(), 'session': used}, who=who) # the guest learns nothing about the VM: not its name, not the cluster return jsonify({'ticket': d['ticket'], 'max_minutes': max_minutes, 'idle_minutes': d.get('idle_minutes')}) diff --git a/dashboard/invite_api.py b/dashboard/invite_api.py index fee61cb..530aec3 100644 --- a/dashboard/invite_api.py +++ b/dashboard/invite_api.py @@ -161,13 +161,18 @@ def _scope(inv: dict) -> dict: 'vm_uuid': inv['vm_uuid'], 'vm_name': inv['vm_name']} -def _link(token: str, host_url: str | None) -> str: - return f'{mailer.link_base(host_url)}/invite/{token}' +def _link(token: str, base: str | None) -> str: + return f"{(base or '').rstrip('/')}/invite/{token}" def _send(inv: dict, token: str, host_url: str | None, by: str) -> dict: - """Mail the link; without mail (or on failure) the link comes back for the inviter to pass on.""" - link = _link(token, host_url) + """Mail the link; without mail (or on failure) the link comes back for the inviter to pass on. + The mailed link uses the configured address in links only: the inviter's request Host header is theirs + to set, so it may only shape the link shown back to the inviter, never one mailed to someone else.""" + base = mailer.link_base() + if not base: + return {'sent': False, 'error': mailer.LINK_ADDRESS_MISSING, 'link': _link(token, host_url)} + link = _link(token, base) if inv['kind'] == 'activate': kind, values = 'activate', {} else: @@ -409,6 +414,7 @@ def sign_in(user_id: str) -> bool: return False session.clear() session['user_id'], session['username'], session['role'] = str(full['user_id']), full['username'], full['role'] + session['gen'] = int(full.get('session_gen') or 0) # the generation the session was started at return True @app.route('/invite/', methods=['GET', 'POST']) diff --git a/dashboard/login_texts.py b/dashboard/login_texts.py index 5c93330..8da5c94 100644 --- a/dashboard/login_texts.py +++ b/dashboard/login_texts.py @@ -23,6 +23,8 @@ 'err_needs_email': 'Your account needs an email address. An administrator will send you an invitation.', 'err_awaiting': 'Your account is waiting for an administrator to assign its access.', 'err_disabled': 'Your account is disabled. Ask an administrator.', + 'err_locked': 'Too many failed sign-in attempts. Wait 15 minutes and try again.', + 'err_otp_restart': 'Too many wrong codes. Sign in with your password again.', }, 'nl': { 'title': 'Aanmelden', 'tagline': 'Beheeromgeving voor clusters', @@ -39,6 +41,8 @@ 'err_needs_email': 'Je account heeft een e-mailadres nodig. Een beheerder stuurt je een uitnodiging.', 'err_awaiting': 'Je account wacht tot een beheerder er toegang aan geeft.', 'err_disabled': 'Je account is uitgeschakeld. Vraag het een beheerder.', + 'err_locked': 'Te veel mislukte aanmeldpogingen. Wacht 15 minuten en probeer het opnieuw.', + 'err_otp_restart': 'Te veel onjuiste codes. Meld je opnieuw aan met je wachtwoord.', }, 'de': { 'title': 'Anmelden', 'tagline': 'Verwaltungsoberfläche für Cluster', @@ -55,6 +59,8 @@ 'err_needs_email': 'Ihr Konto braucht eine E-Mail-Adresse. Ein Administrator sendet Ihnen eine Einladung.', 'err_awaiting': 'Ihr Konto wartet darauf, dass ein Administrator ihm Zugriff gibt.', 'err_disabled': 'Ihr Konto ist deaktiviert. Wenden Sie sich an einen Administrator.', + 'err_locked': 'Zu viele fehlgeschlagene Anmeldeversuche. Warten Sie 15 Minuten und versuchen Sie es erneut.', + 'err_otp_restart': 'Zu viele falsche Codes. Melden Sie sich erneut mit Ihrem Passwort an.', }, 'fr': { 'title': 'Connexion', 'tagline': 'Interface de gestion des clusters', @@ -71,6 +77,8 @@ 'err_needs_email': 'Votre compte a besoin d\'une adresse e-mail. Un administrateur vous enverra une invitation.', 'err_awaiting': 'Votre compte attend qu\'un administrateur lui attribue un accès.', 'err_disabled': 'Votre compte est désactivé. Adressez-vous à un administrateur.', + 'err_locked': 'Trop de tentatives de connexion échouées. Attendez 15 minutes et réessayez.', + 'err_otp_restart': 'Trop de codes incorrects. Reconnectez-vous avec votre mot de passe.', }, } diff --git a/dashboard/mail_api.py b/dashboard/mail_api.py index eb12371..781f2c9 100644 --- a/dashboard/mail_api.py +++ b/dashboard/mail_api.py @@ -21,7 +21,11 @@ def actor() -> str: @requires('install.manage', 'root') def mail_settings_get(): out = mailer.settings() - out['suggested_public_url'] = request.host_url.rstrip('/') + out['suggested_public_url'] = request.host_url.rstrip('/') # a placeholder for the admin, never used in a mail + # links in mails come from public_url only: without it no reset, invitation or approval link is mailed + out['public_url_missing'] = bool(out.get('configured') and not out.get('public_url')) + if out['public_url_missing']: + out['warning'] = mailer.LINK_ADDRESS_MISSING out['env_guest_url'] = (os.getenv('HCM_GUEST_BASE_URL') or '').strip().rstrip('/') or None return jsonify(out) diff --git a/dashboard/mailer.py b/dashboard/mailer.py index e4fb247..3c659a8 100644 --- a/dashboard/mailer.py +++ b/dashboard/mailer.py @@ -89,6 +89,10 @@ def save(body: dict, actor: str) -> dict: if name and any(c in name for c in '\r\n'): raise AccessError('the sender name cannot contain line breaks') url = _link_address(body.get('public_url'), 'the address in links') + if host and not url: + # the links in reset, invitation and approval mails are built from it, never from a request's Host header + raise AccessError('the address in links is required: password reset links and invitations are built from it ' + '(the address people open HCM with, e.g. https://hcm.example.com)') guest_url = _link_address(body.get('guest_url'), 'the address in guest links') username = str(body.get('username') or '').strip()[:200] or None conn = access_db._connect() @@ -143,13 +147,19 @@ def guest_link_base() -> str | None: return (url or (os.getenv('HCM_GUEST_BASE_URL') or '').strip()).rstrip('/') or None -def link_base(request_host_url: str | None = None) -> str: - """The address put in links: the setting, else the address this request came in on.""" +def link_base() -> str | None: + """The address put in links that are mailed: the setting (Settings -> Mail, "Address in links"), or None. + Never the address a request came in on: its Host header is the sender's to choose, so an unauthenticated + 'forgot password' with Host: evil.example would mail the account holder a genuine link to the attacker. + Callers that get None send no link (and say why); an inviter may still be shown a link to pass on.""" try: url = settings().get('public_url') except Exception: # noqa: BLE001 url = None - return (url or (request_host_url or '')).rstrip('/') + return (url or '').strip().rstrip('/') or None + + +LINK_ADDRESS_MISSING = 'the address in links is not set (Settings → Mail): no link can be mailed' # ── sending ───────────────────────────────────────────────────────────────────────────────────────── @@ -210,6 +220,8 @@ def deliver(to: str, kind: str, lang: str | None = None, by: str | None = None, _send(cfg, to, subject, body) except MailError as exc: return _failed(to, kind, by, str(exc)) + except Exception as exc: # noqa: BLE001 — e.g. a line break in a header (ValueError): the promise is never to raise + return _failed(to, kind, by, f'the mail could not be made: {exc.__class__.__name__}: {exc}'[:300]) return {'sent': True, 'error': None} diff --git a/dashboard/reports/pdf_report.py b/dashboard/reports/pdf_report.py index c953dbd..aeff922 100644 --- a/dashboard/reports/pdf_report.py +++ b/dashboard/reports/pdf_report.py @@ -20,6 +20,7 @@ import io import logging from datetime import datetime, timezone +from xml.sax.saxutils import escape as _esc # text that goes into Paragraph markup log = logging.getLogger(__name__) @@ -68,6 +69,13 @@ def _pct(val: float | None) -> str: return f'{val:.1f}%' +def _days_key(e: dict) -> int: + """Sort key: days until exhaustion, with an exhaustion already reached (0) first and an + unknown one last. `or 999` sorted the 0s last and dropped them from the top five.""" + days = e.get('days_until_exhaustion') + return 999 if days is None else days + + def _light_table(story, rows, col_widths, accent_hex, severity_col=None, header_rows=1): """Append a print-friendly table: colored header, white/light-gray rows.""" @@ -246,12 +254,12 @@ def _hr(): under_vms = [r for r in rightsizing if r.get('sizing_direction') == 'under_provisioned'] total_reclaim = sum(float(r.get('capacity_reclaim_cpu_pct') or 0) for r in resize) - # group forecasts by node for overview + # group forecasts by node for overview; the cluster-wide rows (no node) form a 'Cluster' row node_data: dict[str, dict] = {} for f in forecasts: if f.get('forecast_horizon_days') != 30: continue - node = _short(f.get('node_uuid')) + node = _short(f.get('node_uuid')) if f.get('node_uuid') else 'Cluster' dim = f.get('resource_dimension') or '' if dim not in ('cpu', 'storage_capacity'): continue @@ -292,9 +300,9 @@ def _hr(): fontName='Helvetica-Bold', spaceBefore=0, spaceAfter=10))) if company_name: - story.append(_body(f'Prepared for: {company_name}')) + story.append(_body(f'Prepared for: {_esc(company_name)}')) - story.append(_muted(f"Cluster: {data.get('cluster_id', '—')}")) + story.append(_muted(f"Cluster: {_esc(str(data.get('cluster_id', '—')))}")) story.append(_muted(f"Generated: {data.get('generated_at', '—')}")) story.append(Spacer(1, 10*mm)) @@ -339,7 +347,7 @@ def _hr(): # ── KPI cards ───────────────────────────────────────────────────────────── vm_count = len(set(r.get('vm_name') for r in rightsizing)) - node_count = len(node_data) or '?' + node_count = len([n for n in node_data if n != 'Cluster']) or '?' # the cluster-wide row is no node card_w = W / 5 - 8 kpi_row = Table( @@ -375,7 +383,7 @@ def _hr(): story.append(_body( f'The HyperCore cluster is currently {sev_desc}, ' f'scoring {health_score:.0f} out of 100. ' - f'The primary bottleneck is {bottleneck.replace("_", " ")}. ' + f'The primary bottleneck is {_esc(bottleneck.replace("_", " "))}. ' f'Overall resource efficiency stands at {efficiency:.0%}, indicating that a ' f'{"significant" if efficiency < 0.4 else "moderate"} portion of allocated compute ' f'capacity is sitting idle.' @@ -384,16 +392,17 @@ def _hr(): # exhaustion findings if exhaustion: story.append(_h3('Capacity Risk')) - for e in sorted(exhaustion, key=lambda x: x.get('days_until_exhaustion') or 999)[:5]: + for e in sorted(exhaustion, key=_days_key)[:5]: dim = (e.get('resource_dimension') or '—').replace('_', ' ') days = e.get('days_until_exhaustion') exd = e.get('exhaustion_date') or '—' sev2 = e.get('severity') or 'INFO' - node = _short(e.get('node_uuid')) - urgency = 'is imminent' if (days or 999) <= 30 else 'is approaching' + where = f'on node {_short(e.get("node_uuid"))}' if e.get('node_uuid') else 'cluster-wide' + urgency = 'is imminent' if days is not None and days <= 30 else 'is approaching' + left = '—' if days is None else ('reached' if days <= 0 else f'{days} days') story.append(_bullet( - f'{dim.title()} exhaustion on node {node} {urgency} — ' - f'projected {exd} ({days} days). Severity: {sev2}.' + f'{_esc(dim.title())} exhaustion {where} {urgency} — ' + f'projected {_esc(str(exd))} ({left}). Severity: {_esc(sev2)}.' )) else: story.append(_body('No active resource exhaustion alerts. All dimensions have sufficient runway.')) @@ -552,7 +561,7 @@ def _hr(): cur = _pct(e.get('current_usage_pct')) gr = f'{float(e.get("growth_rate_per_day") or 0):.2f}/d' exd = str(e.get('exhaustion_date') or '—') - days = str(e.get('days_until_exhaustion') or '—') + days = '—' if e.get('days_until_exhaustion') is None else str(e.get('days_until_exhaustion')) sev2 = e.get('severity') or 'INFO' ex_rows.append([dim, node, cur, gr, exd, days, sev2]) _light_table(story, ex_rows, @@ -604,7 +613,7 @@ def _hr(): if company_name: footer_parts.append(f'Prepared for {company_name}') footer_parts.append(f'Generated {data.get("generated_at", "")}') - story.append(_muted(' · '.join(footer_parts))) + story.append(_muted(_esc(' · '.join(footer_parts)))) doc.build(story) return buf.getvalue() diff --git a/dashboard/static/access.js b/dashboard/static/access.js index 227eafe..5f7ec81 100644 --- a/dashboard/static/access.js +++ b/dashboard/static/access.js @@ -20,7 +20,7 @@ function hcmModal({ title = '', body = '', buttons = [], closable = true, width
${users.length ? ` - + ${users.map(u => ` - + `).join('')}
${_esc(t('acc.col_email'))}${_esc(t('acc.col_state'))}OTP
${_esc(t('acc.col_state'))}${_esc(t('acc.col_otp'))}
${_esc(u.username)}${u.username === me.username ? ` (${_esc(t('users.you'))})` : ''} ${u.display_name ? `
${_esc(u.display_name)}
` : ''}
${state(u)}${u.otp_enabled ? 'on' : 'off'}${_esc(t(u.otp_enabled ? 'acc.otp_on' : 'acc.otp_off'))}
` : `
${_esc(t('users.none'))}
`}`; @@ -724,7 +733,7 @@ async function _acGroupRender(gid, g) { }).join('') : `
${_esc(t('acc.members_none'))}
`} ${invited.map(i => `
${_acIcon('user')}
${_esc(i.email)}
${_esc(t('acc.tb_invited'))} · ${_esc(_acInviteState(i))}
-
`).join('')} + `).join('')}
${_esc(t('acc.assignments'))} ${_esc(t('acc.group_access_hint'))} @@ -1059,7 +1068,7 @@ async function _acTbPane() { if (box2 && here.length) box2.innerHTML = `
${_esc(t('acc.tb_invited'))} ${here.length}
${here.map(i => `
${_acIcon('user')}
${_esc(i.email)}
${_esc(_acInviteState(i))}
${_esc(i.builtin_key ? t('acc.role_' + i.builtin_key) : (i.role_name || i.group_name || ''))} -
`).join('')}`; +
`).join('')}`; } /** The visible chain from the reader's top down to a node (ids), or null when the node is not theirs to see. */ @@ -1136,7 +1145,7 @@ async function _acInvites() { } function _acInviteState(i) { - return i.state === 'expired' ? t('acc.inv_expired') : t('acc.inv_expires', { at: new Date(i.expires_at).toLocaleString() }); + return i.state === 'expired' ? t('acc.inv_expired') : t('acc.inv_expires', { at: new Date(i.expires_at).toLocaleString(_hcmLocale()) }); } async function _acRenderInvites() { @@ -1151,8 +1160,8 @@ async function _acRenderInvites() { ${_esc(i.kind === 'activate' ? '' : i.scope_label || '')} ${i.invited_by ? _esc(i.invited_by) : _esc(t('acc.actor_above'))} ${_esc(_acInviteState(i))} - - `).join('')} + + `).join('')} ` : ''; } @@ -1360,7 +1369,7 @@ async function _acClusterSave(h, P, clusterId, folderId, force) { else body.folder_id = folderId; if (force) body.force = true; _clMsg(P, t('clusters.testing'), ''); - const r = await fetch(`${API_BASE}/api/clusters${clusterId ? '/' + clusterId : ''}`, + const r = await _netFetch(`${API_BASE}/api/clusters${clusterId ? '/' + clusterId : ''}`, { method: clusterId ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const d = await r.json().catch(() => ({})); if (!r.ok) { @@ -1384,7 +1393,7 @@ async function _acClustersChanged() { async function acClusterTest(cid) { await clTestExisting(cid); } async function acClusterToggle(cid, enabled) { - const r = await fetch(`${API_BASE}/api/clusters/${cid}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled }) }); + const r = await _netFetch(`${API_BASE}/api/clusters/${cid}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled }) }); if (!r.ok) { const d = await r.json().catch(() => ({})); hcmAlert(d.error || `HTTP ${r.status}`); return; } await _acClustersChanged(); } @@ -1393,7 +1402,7 @@ async function acClusterRemove(cid) { if (!c) return; if (!await hcmConfirm(t('clusters.confirm_remove', { name: c.name }), { danger: true, typeToConfirm: c.name, confirmLabel: t('clusters.remove') })) return; const purge = await hcmConfirm(t('clusters.confirm_purge', { name: c.name }), { danger: true }); - const r = await fetch(`${API_BASE}/api/clusters/${cid}?purge=${purge ? 1 : 0}`, { method: 'DELETE' }); + const r = await _netFetch(`${API_BASE}/api/clusters/${cid}?purge=${purge ? 1 : 0}`, { method: 'DELETE' }); if (!r.ok) { const d = await r.json().catch(() => ({})); hcmAlert(d.error || `HTTP ${r.status}`); return; } if (currentCluster === cid) { currentCluster = null; try { localStorage.removeItem(CLUSTER_LS_KEY); } catch (_) {} } _ac.tb.cluster = null; @@ -1425,7 +1434,7 @@ async function _acRenderAudit() { const rows = (d && d.rows) || []; body.innerHTML = rows.length ? ` - ${rows.map(r => ` + ${rows.map(r => ``).join('')}
${_esc(t('acc.col_when'))}${_esc(t('acc.col_who'))} ${_esc(t('acc.col_action'))}${_esc(t('acc.col_what'))}
${_esc(new Date(r.at).toLocaleString())}${r.actor_above ? `${_esc(t('acc.actor_above'))}` : _esc(r.actor || '')}
${_esc(new Date(r.at).toLocaleString(_hcmLocale()))}${r.actor_above ? `${_esc(t('acc.actor_above'))}` : _esc(r.actor || '')} ${_esc(r.action)}${_esc(r.target || '')}${r.detail ? `
${_esc(_acDetail(r.detail))}
` : ''}
` : `
${_esc(t('acc.audit_empty'))}
`; } @@ -1655,7 +1664,7 @@ async function gcForm(kind, preset) { function _gcShowSecrets(r, guest) { hcmModal({ - title: _esc(t('gc.secrets_title')), width: 'min(640px, 96vw)', closable: true, + title: _esc(t('gc.secrets_title')), width: 'min(640px, 96vw)', closable: false, // shown once: only Done closes it body: `

${_esc(t('gc.secrets_intro', { guest: guest || '' }))}

${_esc(t('gc.link'))}
diff --git a/dashboard/static/index.html b/dashboard/static/index.html index d1fd266..9ec2f4b 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -114,6 +114,11 @@ .user-menu-who { padding: 6px 10px 8px; font-size: 12px; color: var(--ink-3); border-bottom: 1px solid var(--border); margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; } .user-menu-sep { height: 1px; background: var(--border); margin: 4px 0; } .user-menu a.rail-nav { text-decoration: none; } + /* sign out is a POST (a link could be triggered from another site): buttons that look like the links they replace */ + .logout-form { margin: 0; } + .logout-form button.rail-nav { width: 100%; background: none; border: 0; font: inherit; color: inherit; text-align: left; } + .logout-link { background: none; border: 0; padding: 0; font: inherit; font-size: 12px; color: var(--text-muted); cursor: pointer; } + .logout-link:hover { color: var(--accent-blue); } /* module tabs, inside the bar */ .nav-tabs { display: flex; align-self: stretch; gap: 0; min-width: 0; overflow-x: auto; scrollbar-width: none; } @@ -1044,6 +1049,8 @@ /* ── nav logout button ───────────────────────────────────────────────── */ /* ── data quality banner ──────────────────────────────────────────────── */ + /* clickable elements that are not buttons, made keyboard reachable by _kbdMark() */ + [data-kbd]:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } #dataQualityBanner { display: none; position: fixed; bottom: 0; left: 0; right: 0; z-index: 9999; @@ -1055,6 +1062,8 @@ text-align: center; } #dataQualityBanner.visible { display: block; } + /* the banner is fixed over the bottom of the page: leave room for it so the last table row stays readable */ + body.has-dq-banner { padding-bottom: 56px; } #dataQualityBanner.info { background: linear-gradient(var(--info-bg), var(--info-bg)), var(--surface); border-top-color: var(--info); color: var(--info); } #dataQualityBanner.warn { background: linear-gradient(var(--warn-bg), var(--warn-bg)), var(--surface); border-top-color: var(--warn); color: var(--warn); } @@ -1159,9 +1168,9 @@
-
Connecting...
+
Connecting...
- +
- - + + 2hr - - - - + + + +
@@ -1265,10 +1274,10 @@ - - - - + + + +
@@ -1423,7 +1432,7 @@
-
@@ -1509,18 +1518,18 @@
-
-