From 838ebb8d1c738f4767ec7c5f499452174427a8aa Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sat, 21 Nov 2026 22:04:15 +0100 Subject: [PATCH 1/7] feat(backup): test restores (boot test and network test on a test VLAN) A test plan per folder restores the newest backup of its VMs as temporary VMs, starts them, checks they come up and deletes them again (plans/PLAN-test-restores.md, T1 + T2). - Rounds every N days: fixed VMs plus N at random from the folder's backed-up VMs, longest untested first, a tested VM rests N weeks; never-test exclusions. - Target: the folder's DR cluster (any hour, paused during the folder's backups), else the VM's own cluster inside the plan's hours, outside backups, only when it fits before the next backups. One test per target cluster; a node must take the VM under the RAM ceiling. - Boot test: NICs disconnected; pass = guest agent answering, else a login/lock/sign-in screen via the console service (new POST /api/v1/bootcheck, classify.boot_verdict recognising stop screens, BitLocker recovery, no bootable device, GRUB rescue, emergency mode as failures). Screenshot kept; agentless VMs marked. - Network test: NICs on an isolated test VLAN (refused when another VM uses it), then ping/TCP checks from a proxy NIC on that VLAN (proxy 0.6.0 job netcheck, bound to that NIC; host routes for the check only; infrastructure addresses never probed). - Proxy deploy: optional test-VLAN NIC; proxies now run with --network host. - Keep-failed and byte budget per round: options, off by default. - Results on Runs (verdict, target, point age, times, checks, screenshot), Tested column on restore points, alerts (test_failed, test_overdue) on the cluster card and mailed to the closest admin. Sweep removes leftover test VMs (tag and name mark both required). - Migration 053. Texts in en/nl/de/fr. Manual, administration guide, CHANGELOG. --- backup/api.py | 249 +++++++++++- backup/db.py | 216 ++++++++++- backup/deploy.py | 17 +- backup/restore.py | 10 +- backup/scheduler.py | 44 +++ backup/testrestore.py | 564 ++++++++++++++++++++++++++++ console/api.py | 15 + console/classify.py | 47 +++ dashboard/app.py | 15 +- dashboard/backup_scope.py | 2 +- dashboard/mail_texts.py | 16 + dashboard/static/index.html | 178 ++++++++- dashboard/static/lang/de.js | 80 ++++ dashboard/static/lang/en.js | 80 ++++ dashboard/static/lang/fr.js | 80 ++++ dashboard/static/lang/nl.js | 80 ++++ dashboard/verify_mail.py | 8 +- docker-compose.yaml | 2 + docs/CHANGELOG.md | 24 ++ docs/administration.md | 5 +- docs/manual/05-backup.md | 41 +- postgres/init/053_test_restores.sql | 89 +++++ proxy/Dockerfile | 4 +- proxy/api.py | 3 +- proxy/identity.py | 14 +- proxy/jobs.py | 15 +- proxy/netcheck.py | 138 +++++++ tests/test_backup_deploy.py | 8 + tests/test_backup_testrestore.py | 294 +++++++++++++++ tests/test_console.py | 28 ++ tests/test_proxy.py | 57 ++- 31 files changed, 2389 insertions(+), 34 deletions(-) create mode 100644 backup/testrestore.py create mode 100644 postgres/init/053_test_restores.sql create mode 100644 proxy/netcheck.py create mode 100644 tests/test_backup_testrestore.py diff --git a/backup/api.py b/backup/api.py index e596b01..a637142 100644 --- a/backup/api.py +++ b/backup/api.py @@ -154,6 +154,9 @@ def chain_owner(chain): if kind == 'proxy': p = db.get_proxy(num) return {'cluster_id': str(p['cluster_id']), 'vm_uuid': None} if p else None + if kind == 'test_run': + t = db.get_test_run(num) + return {'cluster_id': t['cluster_id'], 'vm_uuid': t['vm_uuid']} if t else None if kind == 'change': c = vmedit.get(num) return {'cluster_id': str(c['cluster_id']), 'vm_uuid': c.get('vm_uuid') or None, 'kind': c.get('kind')} if c else None @@ -371,6 +374,11 @@ def _verify_notices(cid: str) -> list: return [] out = [] for a in alerts: + if a['kind'] in ('test_failed', 'test_overdue'): + out.append({'key': f"{a['kind']}:{a.get('vm_uuid')}", 'kind': a['kind'], + 'severity': 'critical' if a['kind'] == 'test_failed' else 'warning', 'vm': a.get('vm_name'), + 'detail': a.get('detail') or '', 'since': a['created_at'].isoformat() if a.get('created_at') else None}) + continue failed = a['kind'] == 'failed' out.append({'key': f"verify_{a['kind']}:{a['point_id'] if failed else a['chain_id']}", 'kind': f"verify_{a['kind']}", 'severity': 'critical' if failed else 'warning', @@ -1230,6 +1238,238 @@ def chains_list(): return jsonify(rows) +# ----------------------------------------------------------- test restores +def _test_plan_fields(b: dict, creating: bool) -> dict: + f = {} + if creating or 'name' in b: + name = str(b.get('name') or '').strip() + if not name or len(name) > 100: + raise ValueError('a name is required (at most 100 characters)') + f['name'] = name + ints = {'interval_days': (1, 90), 'random_count': (0, 50), 'rest_weeks': (1, 52), 'timeout_minutes': (2, 120)} + for k, (lo, hi) in ints.items(): + if k in b: + try: + v = int(b[k]) + except (TypeError, ValueError): + raise ValueError(f'{k} must be a whole number') from None + if not lo <= v <= hi: + raise ValueError(f'{k} must be between {lo} and {hi}') + f[k] = v + for k, (lo, hi) in {'keep_failed_hours': (1, 168), 'byte_budget_gb': (1, 1000000)}.items(): + if k in b: # empty / null: the option is off + if b[k] in (None, '', 0, '0', False): + f[k] = None + else: + try: + v = int(b[k]) + except (TypeError, ValueError): + raise ValueError(f'{k} must be a whole number') from None + if not lo <= v <= hi: + raise ValueError(f'{k} must be between {lo} and {hi}') + f[k] = v + if 'enabled' in b: + f['enabled'] = bool(b['enabled']) + for k in ('hours_from', 'hours_until'): + if k in b: + t = recurrence.parse_hhmm(b[k]) + f[k] = f'{t.hour:02d}:{t.minute:02d}' + if 'level' in b: + if b['level'] not in ('boot', 'network'): + raise ValueError("level must be 'boot' or 'network'") + f['level'] = b['level'] + if 'test_vlan' in b: + if b['test_vlan'] in (None, ''): + f['test_vlan'] = None + else: + v = int(b['test_vlan']) + if not 0 <= v <= 4094: + raise ValueError('the test VLAN must be between 0 and 4094') + f['test_vlan'] = v + if 'probe_address' in b: + pa = str(b.get('probe_address') or '').strip() or None + if pa: + import ipaddress + try: + iface = ipaddress.IPv4Interface(pa) + except ValueError: + raise ValueError('the probe address must be an IPv4 address with its prefix, e.g. 172.16.0.250/25') from None + if iface.network.prefixlen == 32 or '/' not in pa: + raise ValueError("the probe address needs the test subnet's prefix, e.g. /24") + f['probe_address'] = pa + if 'default_ports' in b: + f['default_ports'] = _ports(b['default_ports']) + return f + + +def _ports(v) -> list: + items = v if isinstance(v, list) else [x for x in str(v or '').replace(';', ',').replace(' ', ',').split(',') if x] + out = [] + for x in items: + try: + p = int(x) + except (TypeError, ValueError): + raise ValueError(f'{x!r} is not a port number') from None + if not 1 <= p <= 65535: + raise ValueError(f'{p} is not a port number (1-65535)') + if p not in out: + out.append(p) + return out[:20] + + +def _check_network_plan(plan: dict) -> None: + if plan.get('level') == 'network' and (plan.get('test_vlan') is None or not plan.get('probe_address')): + raise ValueError('a network test needs a test VLAN and the proxy\'s probe address on it') + + +def _test_plan_in_scope(pid: int): + folder, err = _scope() + if err: + return None, err + plan = db.get_test_plan(pid) + if not plan or plan['folder_id'] != folder: + return None, _err('test plan not found', 404) + return plan, None + + +@app.get('/api/v1/test-plans') +@_require_token +def test_plans_list(): + """The folder's test plans with their members, where tests run, which proxies can run network checks, + and the backed-up VMs to pick from.""" + folder, err = _scope() + if err: + return err + import testrestore + clusters = db.folder_clusters(folder) + proxies = [] + for c in clusters: + for p in db.get_proxies(c['cluster_id'], enabled_only=True): + caps = p.get('capabilities') or {} + proxies.append({'id': p['id'], 'name': p.get('name'), 'cluster_id': c['cluster_id'], 'cluster_name': c['cluster_name'], + 'role': c['role'], 'version': p.get('version'), + 'host_network': bool(caps.get('host_network')) and 'netcheck' in (caps.get('jobs') or [])}) + plans = [] + for pl in db.get_test_plans(folder): + d = dict(pl, members=db.test_plan_vms(pl['id'])) + plans.append(d) + return jsonify(_plain({'folder_id': folder, 'folder_name': db.folder_name(folder) if folder else None, + 'clusters': clusters, 'proxies': proxies, 'plans': plans, 'vms': db.backed_up_vms(folder), + 'running': list(testrestore.running().values())})) + + +@app.post('/api/v1/test-plans') +@_require_token +def test_plans_create(): + folder, err = _scope() + if err: + return err + b = request.get_json(silent=True) or {} + try: + f = _test_plan_fields(b, True) + _check_network_plan(f) + except (ValueError, recurrence.RecurrenceError) as e: + return _err(str(e)) + pid = db.add_test_plan(folder, (str(b.get('updated_by') or '').strip() or None), **f) + return jsonify({'ok': True, 'id': pid}), 201 + + +@app.put('/api/v1/test-plans/') +@_require_token +def test_plans_update(pid): + plan, err = _test_plan_in_scope(pid) + if err: + return err + b = request.get_json(silent=True) or {} + try: + f = _test_plan_fields(b, False) + _check_network_plan(dict(plan, **f)) + except (ValueError, recurrence.RecurrenceError) as e: + return _err(str(e)) + db.update_test_plan(pid, (str(b.get('updated_by') or '').strip() or None), **f) + return jsonify({'ok': True}) + + +@app.delete('/api/v1/test-plans/') +@_require_token +def test_plans_delete(pid): + plan, err = _test_plan_in_scope(pid) + if err: + return err + db.delete_test_plan(pid) + return jsonify({'ok': True}) + + +@app.post('/api/v1/test-plans//run') +@_require_token +def test_plans_run(pid): + """Queue a round now (it runs when the target may take it, like a scheduled one).""" + plan, err = _test_plan_in_scope(pid) + if err: + return err + import testrestore + n = testrestore.queue_round(plan, datetime.now(timezone.utc)) + return jsonify({'ok': True, 'queued': n}) + + +@app.post('/api/v1/test-plans//vms') +@_require_token +def test_plans_vm_set(pid): + """{cluster_id, vm_uuid, vm_name, mode: fixed | exclude, ports?}""" + plan, err = _test_plan_in_scope(pid) + if err: + return err + b = request.get_json(silent=True) or {} + cid, vm = str(b.get('cluster_id') or ''), str(b.get('vm_uuid') or '').strip() + if not cluster_registry.is_uuid(cid) or not vm: + return _err('cluster_id and vm_uuid required') + known, folder = db.folder_of_cluster(cid) + if not known or folder != plan['folder_id']: + return _err('that VM is not in this folder') + mode = b.get('mode') or 'fixed' + if mode not in ('fixed', 'exclude'): + return _err("mode must be 'fixed' or 'exclude'") + try: + ports = None if b.get('ports') in (None, '') else _ports(b['ports']) + except ValueError as e: + return _err(str(e)) + db.set_test_plan_vm(pid, cid, vm, (str(b.get('vm_name') or '').strip() or None), mode, ports) + return jsonify({'ok': True}) + + +@app.delete('/api/v1/test-plans//vms') +@_require_token +def test_plans_vm_remove(pid): + plan, err = _test_plan_in_scope(pid) + if err: + return err + 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 '') + return jsonify({'ok': True, 'removed': db.remove_test_plan_vm(pid, cid, vm)}) + + +@app.get('/api/v1/test-runs') +@_require_token +def test_runs_list(): + limit = max(1, min(request.args.get('limit', 100, type=int), 500)) + try: + rows = db.test_runs(_clusters_arg(), limit) + except Exception: # noqa: BLE001 — before migration 053 + rows = [] + return jsonify([_ser(r) for r in rows]) + + +@app.get('/api/v1/test-runs//screenshot') +@_require_token +def test_run_screenshot(run_id): + from flask import Response + data = db.test_run_screenshot(run_id) + if data is None: + return _err('no screenshot', 404) + return Response(data, mimetype='image/png') + + # ----------------------------------------------------------- planned verification def _verify_fields(b: dict) -> dict: f = {} @@ -1490,7 +1730,7 @@ def deployments_clear(): @_require_token def deployments_start(): """Create a proxy VM on a cluster from a cloud image. body: {cluster_id, name, vcpu, mem_gb, disk_gb, vlan, - ip:{mode, address, prefix, gateway, dns}, image_url, image_name, authorized_key, tz}""" + 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() @@ -1506,9 +1746,14 @@ def deployments_start(): 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')} + 'authorized_key': (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') + if params['test_vlan'] is not None and not 0 <= params['test_vlan'] <= 4094: + return _err('the test VLAN must be between 0 and 4094') + if params['test_vlan'] is not None and params['test_vlan'] == params['vlan']: + return _err('the test VLAN must differ from the proxy\'s own VLAN') info = proxy_image.stack_image(max_age=0) if not info.get('available'): return _err(f"this installation has no proxy image to push: {info.get('detail') or 'the dashboard did not report one'}", 502) diff --git a/backup/db.py b/backup/db.py index 78e91d0..aedaf48 100644 --- a/backup/db.py +++ b/backup/db.py @@ -669,7 +669,10 @@ def get_chains(cluster_id: Optional[str] = None, vm_uuid: Optional[str] = None, (SELECT MIN(pt.verify_checked_at) FROM backup.points pt WHERE pt.chain_id = ch.id AND pt.status = 'ok') AS verify_oldest, (SELECT MIN(pt.created_at) FROM backup.points pt WHERE pt.chain_id = ch.id AND pt.status = 'ok' AND pt.verify_checked_at IS NULL) AS verify_never_since, - c.folder_id::text AS folder_id + c.folder_id::text AS folder_id, + (SELECT row_to_json(x) FROM (SELECT tr.id, tr.status, tr.verdict, tr.finished_at FROM backup.test_runs tr + WHERE tr.cluster_id = ch.cluster_id AND tr.vm_uuid = ch.vm_uuid AND tr.status IN ('passed', 'failed') + ORDER BY tr.id DESC LIMIT 1) x) AS last_test FROM backup.chains ch LEFT JOIN backup.targets t ON t.id = ch.target_id LEFT JOIN backup.plans p ON p.id = ch.plan_id LEFT JOIN config.clusters c ON c.cluster_id = ch.cluster_id''' @@ -1028,13 +1031,13 @@ def resolve_verify_alerts(point_id: Optional[int] = None, chain_id: Optional[int def resolve_alerts_of_gone_points() -> int: """Alerts of points that were pruned or whose chain was deleted are no longer actionable.""" return _exec('''UPDATE backup.verify_alerts a SET resolved_at = NOW() - WHERE a.resolved_at IS NULL AND ( + WHERE a.resolved_at IS NULL AND a.kind IN ('failed', 'overdue') AND ( (a.point_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM backup.points p WHERE p.id = a.point_id AND p.status = 'ok')) OR NOT EXISTS (SELECT 1 FROM backup.chains c WHERE c.id = a.chain_id AND c.status IN ('active', 'retired')))''') def open_verify_alerts(cluster_id: str) -> list[dict]: - return _all('''SELECT id, kind, chain_id, point_id, vm_name, seq, detail, created_at FROM backup.verify_alerts + return _all('''SELECT id, kind, chain_id, point_id, vm_uuid, vm_name, seq, detail, created_at FROM backup.verify_alerts WHERE cluster_id = %s AND resolved_at IS NULL ORDER BY created_at''', (cluster_id,)) @@ -1078,3 +1081,210 @@ def prune_verify_history(days: int = 90) -> int: n = _exec('DELETE FROM backup.verify_runs WHERE status <> %s AND started_at < NOW() - make_interval(days => %s)', ('running', int(days))) n += _exec('DELETE FROM backup.verify_alerts WHERE resolved_at < NOW() - make_interval(days => %s)', (int(days),)) return n + + +# --------------------------------------------------------------- test restores (053) +_TEST_PLAN_FIELDS = ('name', 'enabled', 'interval_days', 'hours_from', 'hours_until', 'random_count', 'rest_weeks', 'level', + 'test_vlan', 'probe_address', 'default_ports', 'timeout_minutes', 'keep_failed_hours', 'byte_budget_gb') + + +def _test_plan_row(r): + if r is None: + return None + d = dict(r) + d['folder_id'] = str(d['folder_id']) if d.get('folder_id') else None + d['default_ports'] = list(d.get('default_ports') or []) + return d + + +def get_test_plans(folder_id: Optional[str] = None, all_folders: bool = False) -> list[dict]: + if all_folders: + return [_test_plan_row(r) for r in _all('SELECT * FROM backup.test_plans ORDER BY id')] + return [_test_plan_row(r) for r in _all('''SELECT * FROM backup.test_plans + WHERE COALESCE(folder_id, %s::uuid) = COALESCE(%s::uuid, %s::uuid) + ORDER BY lower(name), id''', (_NO_FOLDER, folder_id, _NO_FOLDER))] + + +def get_test_plan(plan_id: int) -> Optional[dict]: + return _test_plan_row(_one('SELECT * FROM backup.test_plans WHERE id = %s', (plan_id,))) + + +def add_test_plan(folder_id: Optional[str], actor: Optional[str], **f) -> int: + cols = [k for k in _TEST_PLAN_FIELDS if k in f] + return _one(f'''INSERT INTO backup.test_plans (folder_id, updated_by, {", ".join(cols)}) + VALUES (%s, %s, {", ".join(["%s"] * len(cols))}) RETURNING id''', [folder_id, actor] + [f[k] for k in cols])['id'] + + +def update_test_plan(plan_id: int, actor: Optional[str] = None, **f) -> None: + items = [(k, v) for k, v in f.items() if k in _TEST_PLAN_FIELDS or k == 'last_run_at'] + if not items: + return + _exec(f'''UPDATE backup.test_plans SET {", ".join(f"{k} = %s" for k, _ in items)}, updated_at = NOW(), + updated_by = COALESCE(%s, updated_by) WHERE id = %s''', [v for _, v in items] + [actor, plan_id]) + + +def delete_test_plan(plan_id: int) -> None: + _exec('DELETE FROM backup.test_plans WHERE id = %s', (plan_id,)) + + +def test_plan_vms(plan_id: int) -> list[dict]: + return [dict(r, cluster_id=str(r['cluster_id']), ports=list(r['ports']) if r.get('ports') is not None else None) + for r in _all('SELECT * FROM backup.test_plan_vms WHERE plan_id = %s ORDER BY vm_name', (plan_id,))] + + +def set_test_plan_vm(plan_id: int, cluster_id: str, vm_uuid: str, vm_name: Optional[str], mode: str, ports) -> None: + _exec('''INSERT INTO backup.test_plan_vms (plan_id, cluster_id, vm_uuid, vm_name, mode, ports) VALUES (%s,%s,%s,%s,%s,%s) + ON CONFLICT (plan_id, cluster_id, vm_uuid) DO UPDATE SET vm_name = EXCLUDED.vm_name, mode = EXCLUDED.mode, + ports = EXCLUDED.ports''', + (plan_id, cluster_id, vm_uuid, vm_name, mode, ports)) + + +def remove_test_plan_vm(plan_id: int, cluster_id: str, vm_uuid: str) -> int: + return _exec('DELETE FROM backup.test_plan_vms WHERE plan_id = %s AND cluster_id = %s AND vm_uuid = %s', (plan_id, cluster_id, vm_uuid)) + + +def backed_up_vms(folder_id: Optional[str]) -> list[dict]: + """VMs of a folder with at least one restorable point in an active chain, with their last test.""" + return _all('''SELECT DISTINCT ON (ch.cluster_id, ch.vm_uuid) ch.cluster_id::text AS cluster_id, ch.vm_uuid, ch.vm_name, + (SELECT MAX(t.finished_at) FROM backup.test_runs t WHERE t.cluster_id = ch.cluster_id + AND t.vm_uuid = ch.vm_uuid AND t.status IN ('passed', 'failed')) AS last_tested + FROM backup.chains ch JOIN config.clusters c ON c.cluster_id = ch.cluster_id + WHERE ch.status = 'active' AND ch.target_id IS NOT NULL AND c.enabled + AND COALESCE(c.folder_id, %s::uuid) = COALESCE(%s::uuid, %s::uuid) + AND EXISTS (SELECT 1 FROM backup.points p WHERE p.chain_id = ch.id AND p.status = 'ok') + ORDER BY ch.cluster_id, ch.vm_uuid, ch.id DESC''', (_NO_FOLDER, folder_id, _NO_FOLDER)) + + +def newest_point_for_vm(cluster_id: str, vm_uuid: str) -> Optional[dict]: + """The newest restorable point of the VM's active chain, with its chain and the bytes a restore writes + (the sum of what the chain's points up to it wrote: an upper bound).""" + return _one('''SELECT p.*, ch.id AS chain_id, ch.vm_name, ch.target_id, ch.chain_dir, ch.folder_slug, + (SELECT COALESCE(SUM(q.bytes_written), 0) FROM backup.points q + WHERE q.chain_id = ch.id AND q.status = 'ok' AND q.seq <= p.seq) AS restore_bytes + FROM backup.points p JOIN backup.chains ch ON ch.id = p.chain_id + WHERE ch.cluster_id = %s AND ch.vm_uuid = %s AND ch.status = 'active' AND p.status = 'ok' + ORDER BY p.created_at DESC, p.seq DESC LIMIT 1''', (cluster_id, vm_uuid)) + + +def queue_test_runs(plan: dict, round_at: datetime, vms: list[dict]) -> int: + n = 0 + with connect() as conn: + with conn.cursor() as c: + # what the previous round did not reach is not carried over: the new round picks again + c.execute('''UPDATE backup.test_runs SET status = 'skipped', finished_at = NOW(), + detail = 'not reached before the next round of this plan' + WHERE plan_id = %s AND status = 'queued' ''', (plan['id'],)) + for v in vms: + c.execute('''INSERT INTO backup.test_runs (plan_id, folder_id, round_at, cluster_id, vm_uuid, vm_name, picked, level) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s)''', + (plan['id'], plan['folder_id'], round_at, v['cluster_id'], v['vm_uuid'], v.get('vm_name'), v['picked'], plan['level'])) + n += 1 + c.execute('UPDATE backup.test_plans SET last_run_at = %s WHERE id = %s', (round_at, plan['id'])) + return n + + +_TEST_RUN_COLS = ('status', 'verdict', 'agent', 'point_id', 'point_created_at', 'target_cluster_id', 'proxy_id', 'restore_id', + 'restored_vm_uuid', 'bytes', 'checks', 'screenshot', 'detail', 'started_at', 'restored_at', 'booted_at', + 'finished_at', 'keep_until', 'cleaned_at') + + +def update_test_run(run_id: int, **f) -> None: + items = [(k, _json(v) if k == 'checks' else (psycopg2.Binary(v) if k == 'screenshot' and v is not None else v)) + for k, v in f.items() if k in _TEST_RUN_COLS] + if items: + _exec(f'UPDATE backup.test_runs SET {", ".join(f"{k} = %s" for k, _ in items)} WHERE id = %s', [v for _, v in items] + [run_id]) + + +_TEST_RUN_SELECT = '''SELECT t.id, t.plan_id, t.folder_id::text AS folder_id, t.round_at, t.cluster_id::text AS cluster_id, t.vm_uuid, + t.vm_name, t.picked, t.level, t.status, t.verdict, t.agent, t.point_id, t.point_created_at, + t.target_cluster_id::text AS target_cluster_id, t.proxy_id, t.restore_id, t.restored_vm_uuid, t.bytes, + t.checks, t.detail, t.queued_at, t.started_at, t.restored_at, t.booted_at, t.finished_at, + t.keep_until, t.cleaned_at, (t.screenshot IS NOT NULL) AS has_screenshot, + c.cluster_name, tc.cluster_name AS target_cluster_name, pl.name AS plan_name + FROM backup.test_runs t LEFT JOIN config.clusters c ON c.cluster_id = t.cluster_id + LEFT JOIN config.clusters tc ON tc.cluster_id = t.target_cluster_id + LEFT JOIN backup.test_plans pl ON pl.id = t.plan_id''' + + +def get_test_run(run_id: int) -> Optional[dict]: + return _one(_TEST_RUN_SELECT + ' WHERE t.id = %s', (run_id,)) + + +def test_runs(cluster_ids, limit: int = 100) -> list[dict]: + if cluster_ids is None: + return _all(_TEST_RUN_SELECT + ' ORDER BY t.id DESC LIMIT %s', (int(limit),)) + ids = cluster_ids if isinstance(cluster_ids, list) else [cluster_ids] + return _all(_TEST_RUN_SELECT + ' WHERE t.cluster_id = ANY(%s::uuid[]) ORDER BY t.id DESC LIMIT %s', (ids, int(limit))) + + +def queued_test_runs() -> list[dict]: + return _all(_TEST_RUN_SELECT + " WHERE t.status = 'queued' ORDER BY t.queued_at, t.id") + + +def test_run_screenshot(run_id: int) -> Optional[bytes]: + r = _one('SELECT screenshot FROM backup.test_runs WHERE id = %s', (run_id,)) + return bytes(r['screenshot']) if r and r.get('screenshot') is not None else None + + +def round_bytes(plan_id: int, round_at) -> int: + r = _one('''SELECT COALESCE(SUM(bytes), 0) AS n FROM backup.test_runs + WHERE plan_id = %s AND round_at = %s AND status NOT IN ('queued', 'skipped')''', (plan_id, round_at)) + return int(r['n']) if r else 0 + + +def interrupted_test_runs() -> int: + return _exec("""UPDATE backup.test_runs SET status = 'error', finished_at = NOW(), + detail = 'Interrupted by a restart; the test VM is removed by the sweep.' WHERE status = 'running'""") + + +def test_vms_to_clean(now: datetime) -> list[dict]: + """Test VMs that are done with: finished (or interrupted), not kept, not deleted yet.""" + return _all('''SELECT id, target_cluster_id::text AS target_cluster_id, restored_vm_uuid FROM backup.test_runs + WHERE restored_vm_uuid IS NOT NULL AND cleaned_at IS NULL AND status NOT IN ('running', 'queued') + AND (keep_until IS NULL OR keep_until < %s)''', (now,)) + + +def test_vms_in_use(now: datetime) -> set: + """Restored test VMs that must stay: running tests, and failed ones kept for inspection.""" + return {r['restored_vm_uuid'] for r in _all('''SELECT restored_vm_uuid FROM backup.test_runs + WHERE restored_vm_uuid IS NOT NULL AND cleaned_at IS NULL + AND (status = 'running' OR keep_until >= %s)''', (now,))} + + +def last_test_passes(plan_id: int) -> dict: + """(cluster_id, vm_uuid) -> last passed finished_at, for a plan's fixed VMs.""" + rows = _all('''SELECT v.cluster_id::text AS cluster_id, v.vm_uuid, v.vm_name, + (SELECT MAX(t.finished_at) FROM backup.test_runs t WHERE t.cluster_id = v.cluster_id AND t.vm_uuid = v.vm_uuid + AND t.status = 'passed') AS passed + FROM backup.test_plan_vms v WHERE v.plan_id = %s AND v.mode = 'fixed' ''', (plan_id,)) + return {(r['cluster_id'], r['vm_uuid']): r for r in rows} + + +def raise_test_alert(kind: str, folder_id: Optional[str], cluster_id: str, vm_uuid: str, vm_name: Optional[str], detail: str) -> bool: + r = _one('''INSERT INTO backup.verify_alerts (kind, folder_id, cluster_id, vm_uuid, vm_name, detail) + VALUES (%s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING RETURNING id''', + (kind, folder_id, cluster_id, vm_uuid, vm_name, (detail or '')[:1000])) + return r is not None + + +def resolve_test_alerts(cluster_id: str, vm_uuid: str, kind: Optional[str] = None) -> int: + sql = "UPDATE backup.verify_alerts SET resolved_at = NOW() WHERE resolved_at IS NULL AND cluster_id = %s AND vm_uuid = %s" + params: list = [cluster_id, vm_uuid] + if kind: + sql += ' AND kind = %s'; params.append(kind) + else: + sql += " AND kind IN ('test_failed', 'test_overdue')" + return _exec(sql, params) + + +def ram_limit_percent(cluster_id: str) -> float: + """The balancer's hard RAM ceiling for the cluster (RAM_LIMIT_PERCENT; the balancer's default is 85).""" + try: + r = _one("SELECT value FROM config.tunables WHERE cluster_id = %s AND key = 'RAM_LIMIT_PERCENT'", (cluster_id,)) + return float(r["value"]) if r else 85.0 + except Exception: # noqa: BLE001 + return 85.0 + + +def running_test_ids() -> list[int]: + return [r['id'] for r in _all("SELECT id FROM backup.test_runs WHERE status = 'running'")] diff --git a/backup/deploy.py b/backup/deploy.py index 2430a3c..976ff7a 100644 --- a/backup/deploy.py +++ b/backup/deploy.py @@ -182,7 +182,9 @@ def handle_error(self, request, client_address): image=$(cat /etc/hcm-proxy/image) modprobe nbd max_part=0 || true docker rm -f hcm-proxy >/dev/null 2>&1 || true -exec docker run -d --name hcm-proxy --restart unless-stopped --privileged --memory 1g -p 8083:8083 \\ +# --network host: the proxy sees the VM's own NICs, which the network checks of test restores need (the +# test-VLAN NIC); it listens on 8083 directly +exec docker run -d --name hcm-proxy --restart unless-stopped --privileged --memory 1g --network host \\ -v /dev:/dev -v /sys:/host/sys:ro -v hcm-proxy-data:/var/lib/hcm-proxy -v /var/lib/hcm-proxy-update:/update \\ -v /etc/hcm-proxy/tls:/etc/hcm-proxy/tls:ro --env-file /etc/hcm-proxy.env "$image" """ @@ -300,12 +302,16 @@ def cloud_init_metadata(hostname: str) -> str: return f'instance-id: {hostname}-{uuidlib.uuid4().hex[:8]}\nlocal-hostname: {hostname}\n' -def vm_body(name: str, vcpu: int, mem_gb: int, vlan: int, userdata: str, metadata: str) -> dict: +def vm_body(name: str, vcpu: int, mem_gb: int, vlan: int, userdata: str, metadata: str, test_vlan: int | None = None) -> dict: """VirDomain create body. HyperCore wants the cloud-init documents base64-encoded (a plain - string is answered with a 500) and builds a NoCloud ISO from them.""" + string is answered with a 500) and builds a NoCloud ISO from them. test_vlan: a second NIC on the + test VLAN for the network checks of test restores (left unconfigured; the proxy brings it up per check).""" b64 = lambda t: base64.b64encode(t.encode()).decode() # noqa: E731 + nics = [{'type': 'VIRTIO', 'vlan': int(vlan or 0), 'connected': True}] + if test_vlan is not None: + nics.append({'type': 'VIRTIO', 'vlan': int(test_vlan), 'connected': True}) return {'dom': {'name': name, 'mem': int(mem_gb) << 30, 'numVCPU': int(vcpu), 'operatingSystem': 'os_other', - 'tags': 'hcm-proxy', 'blockDevs': [], 'netDevs': [{'type': 'VIRTIO', 'vlan': int(vlan or 0), 'connected': True}], + 'tags': 'hcm-proxy', 'blockDevs': [], 'netDevs': nics, 'cloudInitData': {'userData': b64(userdata), 'metaData': b64(metadata)}}, 'options': {'attachGuestToolsISO': False, 'machineTypeKeyword': 'uefi', 'useUEFISecureBoot': False}} @@ -428,7 +434,8 @@ def run_deployment(dep_id: int) -> None: userdata = cloud_init_userdata(token=token, tz=p.get('tz') or 'UTC', hostname=name, ip=p.get('ip'), authorized_key=p.get('authorized_key')) db.update_deployment(dep_id, message='creating the proxy VM') - r = hc._request('POST', '/VirDomain', json=vm_body(name, p.get('vcpu') or 1, p.get('mem_gb') or 2, p.get('vlan') or 0, userdata, cloud_init_metadata(name))) or {} + r = hc._request('POST', '/VirDomain', json=vm_body(name, p.get('vcpu') or 1, p.get('mem_gb') or 2, p.get('vlan') or 0, userdata, cloud_init_metadata(name), + p.get('test_vlan'))) or {} if not r.get('createdUUID'): raise HyperCoreError(f'VM not created: {r}') wait_task(hc, r['taskTag'], 'create VM', 600) diff --git a/backup/restore.py b/backup/restore.py index 0035fa0..58091bc 100644 --- a/backup/restore.py +++ b/backup/restore.py @@ -11,6 +11,7 @@ 4. the proxy VM is snapshotted (no clones may be attached at that moment) and the staging disks are cloned onto the restored VM; staging disks and snapshot are removed 5. boot order, MAC/VLAN policy, optional start +Test restores (testrestore.py) pass extra_tags, a description, and on the network level a VLAN for every NIC. Step 0, on by default: the backing chain of the point is re-hashed on the proxy first. Only one restore or backup runs per proxy at a time (the proxy VM cannot be snapshotted while @@ -159,8 +160,9 @@ def _run(r: dict) -> None: # 2. import the diskless VM db.update_restore(rid, message='importing definition') source_uri = jobs.build_path_uri(f"{share['uri_base'].rstrip('/')}/{out_dir}", share.get('username') or None, share.get('password') or None) - tag, created = hc.import_vm(source_uri, name=name, description=definition.get('description') or '', tags=definition.get('tags') or '', - definition_file=f'{dirname}.xml') + 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') 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: @@ -220,7 +222,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('vlan') is not None: + 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: fields['vlan'] = old_nic['vlan'] if use_original_mac and old_nic.get('macAddress'): fields['macAddress'] = old_nic['macAddress'] diff --git a/backup/scheduler.py b/backup/scheduler.py index 84c309b..82f4958 100644 --- a/backup/scheduler.py +++ b/backup/scheduler.py @@ -209,6 +209,43 @@ def verify_overdue() -> None: log.info('verification alerts: %s', out) except Exception: # noqa: BLE001 log.debug('overdue check failed', exc_info=True) + import testrestore + try: + out = testrestore.check_overdue() + if out['raised']: + log.info('test restore alerts: %s', out) + except Exception: # noqa: BLE001 + log.debug('test overdue check failed', exc_info=True) + + +def test_tick() -> None: + """Every minute: queue due test-restore rounds and start what may start (testrestore.py).""" + import testrestore + try: + testrestore.tick() + except Exception: # noqa: BLE001 — database not migrated yet, or down + log.debug('test restore tick failed', exc_info=True) + + +def test_sweep() -> None: + """Test VMs whose test is done (kept failures once their time is up), and leftovers of a restart.""" + import testrestore + try: + n = testrestore.sweep() + if n: + log.info('test restore sweep: %s test VM(s) deleted', n) + except Exception: # noqa: BLE001 + log.exception('test restore sweep failed') + + +def _test_reconcile() -> None: + try: + n = db.interrupted_test_runs() + if n: + log.warning('%d test restore(s) were interrupted by a restart; their VMs are removed by the sweep', n) + except Exception: # noqa: BLE001 + log.debug('test reconcile skipped (database not ready)', exc_info=True) + test_sweep() def _verify_reconcile() -> None: @@ -260,6 +297,13 @@ def start(sync_interval_seconds: int = 60) -> None: next_run_time=_dt.now() + _td(seconds=90)) _scheduler.add_job(verify_overdue, trigger='interval', minutes=10, id='verify-overdue', replace_existing=True, next_run_time=_dt.now() + _td(seconds=150)) + # test restores: one tick a minute, a sweep of finished test VMs every 15 minutes (and once after a restart) + _scheduler.add_job(_test_reconcile, trigger='date', run_date=_dt.now() + _td(seconds=200), id='test-reconcile', + replace_existing=True) + _scheduler.add_job(test_tick, trigger='interval', seconds=60, id='test-tick', replace_existing=True, + next_run_time=_dt.now() + _td(seconds=240)) + _scheduler.add_job(test_sweep, trigger='interval', minutes=15, id='test-sweep', replace_existing=True, + 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) diff --git a/backup/testrestore.py b/backup/testrestore.py new file mode 100644 index 0000000..1f392e3 --- /dev/null +++ b/backup/testrestore.py @@ -0,0 +1,564 @@ +""" +testrestore.py — test restores (plans/PLAN-test-restores.md, T1 boot test + T2 network test). + +Verification proves a point's bytes are what was written; a test restore proves the VM boots from them. + +A **test plan** belongs to a folder. Every interval it queues a round: its fixed VMs plus N picked at random +from the folder's backed-up VMs (longest untested first; a tested VM rests N weeks). The tick (once a minute) +runs the queued tests, one at a time per target cluster: + +1. Target: the folder's **DR cluster** when it has one with a proxy, else the VM's own cluster. On a DR cluster + a test may run at any hour (paused while the folder's backups write to the share); on a production cluster + only inside the plan's hours, when that cluster has no backup work running or due, and when the test is + predicted to finish before the next backups. +2. Free memory: some node of the target must take the VM without passing the balancer's RAM ceiling. +3. Restore the newest point as `-hcmtest-`, tagged `hcm-testrestore`, new MAC addresses, and start it: + NICs **disconnected** (boot level) or on the plan's **isolated test VLAN** (network level; refused when any + other VM on that cluster uses that VLAN). The chain is not re-verified first: the planned verification does + that, and a test is about booting. +4. Sign of life: the guest agent answering (works without network) = pass by agent; else the console screen + through the console service: a login, lock or sign-in screen = pass by screen; a stop screen, recovery-key + prompt or nothing to boot = fail; nothing within the timeout = fail. The last screenshot is kept either way. +5. Network level: ping and TCP checks of the VM's addresses, run by a proxy of the target cluster through its + NIC on the test VLAN (proxy job `netcheck`): HCM never touches the test VLAN. +6. Power off and delete the test VM (a failed one is kept N hours when the plan asks). The sweep deletes any + leftover; it only ever touches VMs that carry both the tag and the name mark. + +A failed test raises an alert (cluster card + mail to the closest admin, like verification); a fixed VM without +a passed test for twice the interval raises an 'overdue' one. A pass closes both. +""" +from __future__ import annotations + +import base64 +import json +import logging +import random +import threading +import time +import urllib.request +from datetime import datetime, timedelta, timezone +from urllib.parse import urlparse + +import db +import incremental +import jobs +import verifier +from hypercore import HyperCoreError +from incremental import IncrementalError +from proxy_client import ProxyError + +log = logging.getLogger('backup.testrestore') + +TAG = 'hcm-testrestore' +NAME_MARK = '-hcmtest-' +DEFAULT_RATE = 50 * 1024 * 1024 # bytes/s a restore writes, until measured +POLL_S = 10 +SCREEN_EVERY_S = 30 +FIRST_SCREEN_S = 45 + +_running: dict[str, int] = {} # target cluster id -> test run id +_guard = threading.Lock() + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +# ------------------------------------------------------------------ rounds +def select_vms(plan: dict, now: datetime, rng=random) -> list[dict]: + """The VMs of a new round: the fixed ones, then `random_count` from the pool (backed-up VMs of the folder, + minus fixed and excluded ones, minus those tested within `rest_weeks`), longest untested first.""" + members = db.test_plan_vms(plan['id']) + fixed = [m for m in members if m['mode'] == 'fixed'] + skip = {(m['cluster_id'], m['vm_uuid']) for m in members} + out = [dict(cluster_id=m['cluster_id'], vm_uuid=m['vm_uuid'], vm_name=m.get('vm_name'), picked='fixed') for m in fixed] + if plan.get('random_count'): + rest = now - timedelta(weeks=int(plan.get('rest_weeks') or 4)) + pool = [v for v in db.backed_up_vms(plan['folder_id']) + if (v['cluster_id'], v['vm_uuid']) not in skip and (v.get('last_tested') is None or v['last_tested'] < rest)] + rng.shuffle(pool) # ties broken at random + pool.sort(key=lambda v: v.get('last_tested') or datetime.min.replace(tzinfo=timezone.utc)) + out += [dict(cluster_id=v['cluster_id'], vm_uuid=v['vm_uuid'], vm_name=v.get('vm_name'), picked='random') + for v in pool[:int(plan['random_count'])]] + return out + + +def queue_due(now: datetime) -> int: + n = 0 + for plan in db.get_test_plans(all_folders=True): + if not plan['enabled']: + continue + last = plan.get('last_run_at') + if last and last > now - timedelta(days=int(plan['interval_days'])): + continue + n += queue_round(plan, now) + return n + + +def queue_round(plan: dict, now: datetime) -> int: + vms = select_vms(plan, now) + n = db.queue_test_runs(plan, now, vms) + log.info("test plan '%s': %s test(s) queued", plan['name'], n) + return n + + +# ------------------------------------------------------------------ where and when +def target_for(folder_id: str | None, own_cluster: str) -> tuple[str, str]: + """(target cluster id, role): a DR cluster of the folder with an enabled proxy (the one with the most free + memory when there are several), else the VM's own cluster.""" + drs = [c for c in db.folder_clusters(folder_id) if c['role'] == 'dr' + and any(p.get('vm_uuid') for p in db.get_proxies(c['cluster_id'], enabled_only=True))] + if not drs: + return own_cluster, db.cluster_role(own_cluster) + if len(drs) == 1: + return drs[0]['cluster_id'], 'dr' + best, free = drs[0]['cluster_id'], -1 + for c in drs: + try: + f = max_free_memory(jobs.client_for(c['cluster_id']).list_nodes()) + except HyperCoreError: + continue + if f > free: + best, free = c['cluster_id'], f + return best, 'dr' + + +def max_free_memory(nodes: list[dict]) -> int: + return max((int(n.get('memSize') or 0) - int(n.get('totalMemUsageBytes') or 0) for n in nodes if n.get('allowRunningVMs', True)), + default=0) + + +def memory_fits(nodes: list[dict], mem: int, limit_pct: float) -> bool: + """Some node that may run VMs takes `mem` more bytes and stays at or under the RAM ceiling.""" + for n in nodes: + if not n.get('allowRunningVMs', True): + continue + size = int(n.get('memSize') or 0) + if size and (int(n.get('totalMemUsageBytes') or 0) + int(mem)) * 100.0 / size <= limit_pct: + return True + return False + + +def predicted_seconds(restore_bytes: int, timeout_minutes: int) -> float: + return restore_bytes / DEFAULT_RATE * 1.25 + timeout_minutes * 60 + 300 + + +def may_start(plan: dict, role: str, target: dict, folder_id: str | None, now: datetime, need_s: float) -> str | None: + """Why the test may not start now (None: it may).""" + clusters = [c['cluster_id'] for c in db.folder_clusters(folder_id)] + if role == 'dr': + busy = verifier.backup_busy(clusters, folder_id, now) + return f'waiting: {busy}' if busy else None + left = verifier.hours_left(now, target.get('timezone'), plan['hours_from'], plan['hours_until']) + if left is None: + return 'waiting for the plan\'s hours' + busy = verifier.backup_busy([target['cluster_id']], folder_id, now) + if busy: + return f'waiting: {busy}' + free = verifier.seconds_to_backups([target['cluster_id']], folder_id, now, left) + if need_s > free: + return 'waiting: it would not finish before the hours end or the next backups' + return None + + +# ------------------------------------------------------------------ the tick +def tick(now: datetime | None = None, start=None) -> int: + """Queue due rounds, then start what may start: one test per target cluster at a time.""" + now = now or _now() + start = start or _start_thread + try: + queue_due(now) + except Exception: # noqa: BLE001 + log.exception('queueing test rounds failed') + started = 0 + with _guard: + busy = set(_running) + plans = {p['id']: p for p in db.get_test_plans(all_folders=True)} + for run in db.queued_test_runs(): + plan = plans.get(run['plan_id']) + if not plan or not plan['enabled']: + db.update_test_run(run['id'], status='skipped', finished_at=now, detail='the test plan was disabled or deleted') + continue + try: + target, role = target_for(plan['folder_id'], run['cluster_id']) + except Exception as e: # noqa: BLE001 + log.warning('test %s: no target: %s', run['id'], e) + continue + if target in busy: + continue + point = db.newest_point_for_vm(run['cluster_id'], run['vm_uuid']) + if not point: + db.update_test_run(run['id'], status='skipped', finished_at=now, detail='the VM has no restore point any more') + continue + need = predicted_seconds(int(point.get('restore_bytes') or 0), int(plan['timeout_minutes'])) + tinfo = next((c for c in db.folder_clusters(plan['folder_id']) if c['cluster_id'] == target), {'cluster_id': target}) + why = may_start(plan, role, tinfo, plan['folder_id'], now, need) + if why: + continue + if plan.get('byte_budget_gb'): + used = db.round_bytes(plan['id'], run['round_at']) + if used + int(point.get('restore_bytes') or 0) > int(plan['byte_budget_gb']) << 30: + db.update_test_run(run['id'], status='skipped', finished_at=now, + detail=f"byte budget of this round reached ({plan['byte_budget_gb']} GB)") + continue + with _guard: + if target in _running: + continue + _running[target] = run['id'] + busy.add(target) + db.update_test_run(run['id'], status='running', started_at=now, target_cluster_id=target, point_id=point['id'], + point_created_at=point['created_at']) + try: + start(run, plan, target, point) + started += 1 + except Exception: # noqa: BLE001 + log.exception('could not start test %s', run['id']) + with _guard: + _running.pop(target, None) + db.update_test_run(run['id'], status='error', finished_at=_now(), detail='could not be started') + return started + + +def _start_thread(run, plan, target, point) -> None: + threading.Thread(target=run_test, args=(run, plan, target, point), name=f"test-restore-{run['id']}", daemon=True).start() + + +# ------------------------------------------------------------------ one test +class Skip(Exception): + pass + + +class Fail(Exception): + def __init__(self, verdict: str, detail: str): + super().__init__(detail) + self.verdict, self.detail = verdict, detail + + +def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, clock=time.monotonic) -> str: + """One test, start to clean-up. Returns the final status.""" + rid = run['id'] + state = {'restored': None, 'png': None} + status, verdict, detail, checks = 'error', None, None, None + try: + src = jobs.client_for(run['cluster_id']) + source_vm = next((v for v in src.list_vms_full() if v.get('uuid') == run['vm_uuid']), None) + agent = 'unknown' if not source_vm or source_vm.get('state') != 'RUNNING' else \ + ('available' if source_vm.get('guestAgentState') == 'AVAILABLE' else 'unavailable') + db.update_test_run(rid, agent=agent) + hc = jobs.client_for(target) + pf = jobs.preflight(hc) + if not pf['ok']: + raise Skip(f"the target cluster cannot take a restore now: {pf['detail']}") + mem = int((point.get('definition') or {}).get('mem') or 0) + if mem and not memory_fits(hc.list_nodes(), mem, db.ram_limit_percent(target)): + raise Skip(f'not enough free memory on the target cluster for {mem >> 30} GiB without passing the RAM ceiling') + net = plan['level'] == 'network' + probe_proxy = None + if net: + probe_proxy = network_ready(hc, target, plan) # raises Fail with what is missing + restored = restore(run, plan, target, point, net, state) + verdict, detail = watch_boot(hc, target, restored, int(plan['timeout_minutes']) * 60, state, sleep=sleep, clock=clock) + db.update_test_run(rid, booted_at=_now()) + if net: + checks = network_checks(hc, run, plan, restored, source_vm, probe_proxy, point) + ok, why = judge_checks(checks) + if not ok: + raise Fail('network', why) + detail = f'{detail}; network checks passed' + status = 'passed' + except Skip as e: + status, detail = 'skipped', str(e) + except Fail as e: + status, verdict, detail = 'failed', e.verdict, e.detail + except (IncrementalError, HyperCoreError, ProxyError) as e: + status, detail = 'error', str(e)[:1000] + except Exception as e: # noqa: BLE001 + log.exception('test %s failed unexpectedly', rid) + status, detail = 'error', f'unexpected error: {e}'[:1000] + finally: + keep = None + if status == 'failed' and plan.get('keep_failed_hours') and state['restored']: + keep = _now() + timedelta(hours=int(plan['keep_failed_hours'])) + db.update_test_run(rid, status=status, verdict=verdict, detail=detail, checks=checks, finished_at=_now(), + screenshot=state['png'], keep_until=keep) + if state['restored'] and not keep: + cleanup(target, state['restored'], rid) + _alerts(run, plan, status, verdict, detail) + with _guard: + _running.pop(target, None) + log.info('[test %s] %s %s: %s', rid, run.get('vm_name'), status, detail) + return status + + +def restore(run: dict, plan: dict, target: str, point: dict, net: bool, state: dict | None = None) -> str: + """Restore the point as the test VM through the normal restore path; returns the new VM's uuid. The VM is + put in state['restored'] as soon as it exists, so a restore that fails half-way is cleaned up too.""" + import restore as restore_mod + chain = db.get_chain(point['chain_id']) + name = f"{(run.get('vm_name') or 'vm')[:40]}{NAME_MARK}{run['id']}" + params = {'mac_policy': 'new', 'start': True, 'verify': False, 'nic_connected': net, 'extra_tags': [TAG], + 'description': f"HCM test restore #{run['id']} of {run.get('vm_name')} (point {point['created_at']:%Y-%m-%d %H:%M} UTC); " + 'deleted automatically'} + if net: + params['vlan'] = int(plan['test_vlan']) + restore_id = db.add_restore(point, chain, name, params, requested_by='test restore', cluster_id=target) + db.update_test_run(run['id'], restore_id=restore_id) + restore_mod.run_restore(restore_id) + r = db.get_restore(restore_id) or {} + if r.get('created_uuid'): + db.update_test_run(run['id'], restored_vm_uuid=r['created_uuid']) + if state is not None: + state['restored'] = r['created_uuid'] + if r.get('status') != 'COMPLETE': + raise Fail('restore', f"the restore failed: {r.get('message') or 'no detail'}") + if 'Not started' in (r.get('message') or ''): + raise Fail('start', r['message']) + bytes_ = _restore_bytes(r.get('message') or '') + db.update_test_run(run['id'], restored_at=_now(), bytes=bytes_ if bytes_ is not None else point.get('restore_bytes')) + return r['created_uuid'] + + +def _restore_bytes(message: str) -> int | None: + import re + m = re.search(r'(\d+) MiB written', message) + return int(m.group(1)) << 20 if m else None + + +def watch_boot(hc, target: str, vm_uuid: str, timeout_s: float, state: dict, sleep=time.sleep, clock=time.monotonic) -> tuple[str, str]: + """('agent' | 'screen', detail) once the VM shows a sign of life; raises Fail otherwise.""" + t0 = clock() + next_screen = t0 + FIRST_SCREEN_S + last_screen = None + while clock() - t0 < timeout_s: + vm = hc.get_vm(vm_uuid) + if vm.get('state') == 'CRASHED': + _grab(target, vm_uuid, state) + raise Fail('crashed', 'the VM crashed while booting') + if vm.get('state') in ('SHUTOFF', 'SHUTDOWN') and clock() - t0 > 60: + _grab(target, vm_uuid, state) + raise Fail('stopped', 'the VM switched itself off while booting') + if vm.get('guestAgentState') == 'AVAILABLE': + _grab(target, vm_uuid, state) # for the record; the agent decides + return 'agent', f'guest agent answered after {int(clock() - t0)} s' + if clock() >= next_screen: + r = console_bootcheck(target, vm_uuid) + if r.get('png'): + state['png'] = base64.b64decode(r['png']) + last_screen = r.get('detail') + if r.get('verdict') == 'pass': + return 'screen', f"{r.get('detail')} on the console after {int(clock() - t0)} s" + if r.get('verdict') == 'fail': + raise Fail('screen', f"{r.get('detail')} (console after {int(clock() - t0)} s)") + next_screen = clock() + SCREEN_EVERY_S + sleep(POLL_S) + _grab(target, vm_uuid, state) + raise Fail('timeout', f'no sign of life within {int(timeout_s // 60)} min (no guest agent, ' + f"console: {last_screen or 'not read'})") + + +def _grab(target: str, vm_uuid: str, state: dict) -> None: + try: + r = console_bootcheck(target, vm_uuid) + if r.get('png'): + state['png'] = base64.b64decode(r['png']) + except Exception: # noqa: BLE001 — a screenshot is a bonus here + pass + + +def console_bootcheck(cluster_id: str, vm_uuid: str) -> dict: + """The console service's verdict on the VM's screen: {verdict: pass|fail|wait, detail, png}.""" + import os + import hcm_crypto + url = os.environ.get('CONSOLE_API_URL', 'http://console:8084').rstrip('/') + body = json.dumps({'cluster_id': cluster_id, 'vm_uuid': vm_uuid}).encode() + rq = urllib.request.Request(f'{url}/api/v1/bootcheck', data=body, method='POST', + headers={'Content-Type': 'application/json', + 'Authorization': f"Bearer {hcm_crypto.derived_token('console')}"}) + try: + with urllib.request.urlopen(rq, timeout=60) as resp: + return json.loads(resp.read().decode() or '{}') + except Exception as e: # noqa: BLE001 — console service down: keep waiting for the agent + return {'verdict': 'wait', 'detail': f'console service: {e}'} + + +# ------------------------------------------------------------------ network level +def network_ready(hc, target: str, plan: dict) -> dict: + """The proxy that runs the checks, after the VLAN guardrail. Raises Fail with what is missing.""" + vlan = plan.get('test_vlan') + if vlan is None or not plan.get('probe_address'): + raise Fail('setup', 'the plan has no test VLAN or probe address') + users = [v.get('name') for v in hc.list_vms_full() + if TAG not in (v.get('tags') or '').split(',') and not _is_proxy(v) + and any(int(n.get('vlan') or 0) == int(vlan) for n in v.get('netDevs') or [])] + if users: + raise Fail('setup', f"VLAN {vlan} is in use on the target cluster by {', '.join(sorted(users)[:5])}: " + 'a test VLAN must be used by test VMs only (restored VMs keep their addresses and names)') + for p in db.get_proxies(target, enabled_only=True): + if not p.get('vm_uuid'): + continue + caps = p.get('capabilities') or {} + if not caps.get('host_network') or 'netcheck' not in (caps.get('jobs') or []): + continue + try: + pvm = hc.get_vm(p['vm_uuid']) + except HyperCoreError: + continue + nic = next((n for n in pvm.get('netDevs') or [] if int(n.get('vlan') or 0) == int(vlan) and n.get('macAddress')), None) + if nic: + return dict(p, test_mac=nic['macAddress']) + raise Fail('setup', f'no proxy on the target cluster can test VLAN {vlan}: deploy one (1.7.0 or later) with a test NIC on that VLAN') + + +def _is_proxy(vm: dict) -> bool: + return 'hcm-proxy' in (vm.get('tags') or '').split(',') + + +def network_checks(hc, run: dict, plan: dict, vm_uuid: str, source_vm: dict | None, proxy: dict, point: dict) -> list[dict]: + """Ping and port checks of the test VM's addresses through the proxy's test NIC.""" + ips = _ips(hc.get_vm(vm_uuid)) or _ips(source_vm or {}) or _ips(point.get('definition') or {}) + blocked = _infrastructure(proxy, point) + ips = [ip for ip in ips if ip not in blocked] + if not ips: + raise Fail('network', 'no IPv4 address known for the VM (no guest agent report, none recorded): nothing to check') + member = next((m for m in db.test_plan_vms(plan['id']) if m['cluster_id'] == run['cluster_id'] and m['vm_uuid'] == run['vm_uuid']), None) + ports = (member or {}).get('ports') + ports = list(plan.get('default_ports') or []) if ports is None else ports + full = db.get_proxy(proxy['id'], with_secret=True) or proxy + pc = incremental.proxy_client_for(full) + job = pc.submit('netcheck', {'mac': proxy['test_mac'], 'probe': plan['probe_address'], 'targets': [{'ip': ip, 'ports': ports} for ip in ips]}) + res = pc.wait(job, timeout=300)['result'] or {} + return [{'ip': ip, 'ping': r.get('ping'), 'ports': r.get('ports') or {}} for ip, r in (res.get('results') or {}).items()] + + +def _ips(vm: dict) -> list[str]: + out = [] + for n in vm.get('netDevs') or []: + for ip in n.get('ipv4Addresses') or []: + if ip and not ip.startswith(('127.', '169.254.')) and ip not in out: + out.append(ip) + return out + + +def _infrastructure(proxy: dict, point: dict) -> set: + """Addresses never probed through the test NIC (their host route would cut the proxy off for the check).""" + out = set() + host = urlparse(proxy.get('url') or '').hostname + if host: + out.add(host) + try: + chain = db.get_chain(point['chain_id']) + share = db.get_share(chain['target_id']) if chain and chain.get('target_id') else None + h = urlparse((share or {}).get('uri_base') or '').hostname + if h: + out.add(h) + except Exception: # noqa: BLE001 + pass + return out + + +def judge_checks(checks: list[dict]) -> tuple[bool, str]: + """Pass when one of the VM's addresses answers on every port asked for (with no ports asked for: answers + ping). Windows answers no ping by default, so ports are the better check.""" + if not checks: + return False, 'no network result' + for c in checks: + ports = c.get('ports') or {} + if ports and all(ports.values()): + return True, f"{c['ip']} answers on {', '.join(str(p) for p in ports)}" + if not ports and c.get('ping'): + return True, f"{c['ip']} answers ping" + parts = [] + for c in checks: + closed = [str(p) for p, ok in (c.get('ports') or {}).items() if not ok] + parts.append(f"{c['ip']}: " + (f"port(s) {', '.join(closed)} closed" if closed else ('no ping answer' if not c.get('ping') else 'ok'))) + return False, '; '.join(parts) + + +# ------------------------------------------------------------------ clean-up and alerts +def cleanup(cluster_id: str, vm_uuid: str, run_id: int | None = None) -> bool: + """Power off and delete a test VM; only one that carries the tag and the name mark.""" + try: + hc = jobs.client_for(cluster_id) + try: + vm = hc.get_vm(vm_uuid) + except HyperCoreError: + vm = None # already gone + if vm: + if TAG not in (vm.get('tags') or '').split(',') or NAME_MARK not in (vm.get('name') or ''): + log.error('refusing to delete %s (%s): not a test restore VM', vm.get('name'), vm_uuid) + return False + if vm.get('state') not in ('SHUTOFF', 'SHUTDOWN'): + t = hc.vm_action(vm_uuid, 'STOP') + if t: + incremental.wait_task(hc, t, 'power off test VM', 300) + t = hc.delete_vm(vm_uuid) + if t: + incremental.wait_task(hc, t, 'delete test VM', 600) + if run_id: + db.update_test_run(run_id, cleaned_at=_now()) + return True + except Exception as e: # noqa: BLE001 — the sweep tries again + log.warning('test VM %s on %s not deleted yet: %s', vm_uuid, cluster_id, e) + return False + + +def sweep(now: datetime | None = None) -> int: + """Delete finished test VMs (kept ones once their time is up), then any VM on any cluster that carries the + test tag and name mark but belongs to no running or kept test (left behind by a restart).""" + import cluster_registry + now = now or _now() + n = 0 + for r in db.test_vms_to_clean(now): + if r.get('target_cluster_id') and cleanup(r['target_cluster_id'], r['restored_vm_uuid'], r['id']): + n += 1 + keep = db.test_vms_in_use(now) + # a test that is still restoring has created its VM before the VM's uuid is recorded: spare it by name + running_names = {f'{NAME_MARK}{i}' for i in db.running_test_ids()} + for c in cluster_registry.list_enabled(): + try: + vms = jobs.client_for(c.cluster_id).list_vms_full() + except HyperCoreError: + continue + for v in vms: + name = v.get('name') or '' + if any(name.endswith(m) for m in running_names): + continue + if TAG in (v.get('tags') or '').split(',') and NAME_MARK in name and v.get('uuid') not in keep: + if cleanup(c.cluster_id, v['uuid']): + n += 1 + return n + + +def _alerts(run: dict, plan: dict, status: str, verdict: str | None, detail: str | None) -> None: + try: + if status == 'failed': + db.raise_test_alert('test_failed', plan.get('folder_id'), run['cluster_id'], run['vm_uuid'], run.get('vm_name'), + f'{verdict}: {detail}') + elif status == 'passed': + db.resolve_test_alerts(run['cluster_id'], run['vm_uuid']) + except Exception: # noqa: BLE001 + log.warning('test alert bookkeeping failed', exc_info=True) + + +def check_overdue(now: datetime | None = None) -> dict: + """A fixed VM of an enabled plan without a passed test for twice the plan's interval: an 'overdue' alert.""" + now = now or _now() + out = {'raised': 0} + for plan in db.get_test_plans(all_folders=True): + if not plan['enabled']: + continue + limit = now - timedelta(days=2 * int(plan['interval_days'])) + if plan.get('created_at') and plan['created_at'] > limit: + continue # too young to be overdue + for (cid, vm), r in db.last_test_passes(plan['id']).items(): + if r.get('passed') is None or r['passed'] < limit: + since = r['passed'].strftime('%Y-%m-%d') if r.get('passed') else 'never' + if db.raise_test_alert('test_overdue', plan.get('folder_id'), cid, vm, r.get('vm_name'), + f"no passed test restore since {since} (plan '{plan['name']}' tests every {plan['interval_days']} day(s))"): + out['raised'] += 1 + return out + + +def running() -> dict: + with _guard: + return dict(_running) diff --git a/console/api.py b/console/api.py index 8596c53..09c704a 100644 --- a/console/api.py +++ b/console/api.py @@ -156,6 +156,20 @@ async def screenshot(request): wake=settings.get('wake') or 'none') return web.Response(body=await asyncio.to_thread(classify.png, img), content_type='image/png') + async def bootcheck(request): + """Test restores: has this restored VM booted? {verdict: pass|fail|wait, detail, png (base64)}. Wakes the + screen with a Shift tap (harmless on a login screen; a Windows lock screen shows its sign-in prompt).""" + import base64 + b = await _body(request) + cid, vm = _cluster(request, b), _vm(request, b) + try: + img, _ = await consoles.screenshot(http, cid, vm, username='test restore', source='system', wake='shift') + except hc.ConsoleError as e: + return _json({'verdict': 'wait', 'detail': str(e), 'png': None}) + verdict, detail = await asyncio.to_thread(classify.boot_verdict, img, classify.ocr_available()) + data = await asyncio.to_thread(classify.png, img) + return _json({'verdict': verdict, 'detail': detail, 'png': base64.b64encode(data).decode()}) + # --------------------------------------------------- open-session check async def check_get(request): cid = _cluster(request) @@ -238,6 +252,7 @@ async def flags(request): r.add_post(r'/api/v1/grants/{gid:\d+}/end', end_grant) r.add_post('/api/v1/check/verdict', verdict) r.add_post('/api/v1/screenshot', screenshot) + r.add_post('/api/v1/bootcheck', bootcheck) r.add_get('/api/v1/check', check_get) r.add_put('/api/v1/check/settings', check_settings) r.add_post('/api/v1/check/run', check_run) diff --git a/console/classify.py b/console/classify.py index 6de4ecc..e820b67 100644 --- a/console/classify.py +++ b/console/classify.py @@ -187,3 +187,50 @@ def classify(img: Image.Image, refs: Iterable[str] = (), use_ocr: bool = True, o # a shell prompt in view: undecidable without pressing a key, so never a pass and never an alarm return Verdict('unknown', 'only log output on the console, no prompt in view', h) return Verdict('open', 'no lock or login screen recognised', h) + + +# ------------------------------------------------------------------ boot test (test restores) +# a restored VM that is stuck instead of booted (letters only, accents stripped, lower case) +BOOT_FAIL_PHRASES = ( + ('bitlockerrecovery', 'BitLocker recovery screen: the vTPM did not unseal the key'), + ('recoverykey', 'asks for a recovery key'), + ('ranintoaproblem', 'Windows stop screen'), + ('stopcode', 'Windows stop screen'), + ('automaticrepair', 'Windows automatic repair'), + ('startuprepair', 'Windows startup repair'), + ('nobootabledevice', 'no bootable device'), + ('bootdevicenotfound', 'boot device not found'), + ('operatingsystemnotfound', 'operating system not found'), + ('bootfailed', 'boot failed'), + ('kernelpanic', 'kernel panic'), + ('grubrescue', 'GRUB rescue prompt'), + ('emergencymode', 'Linux emergency mode'), + ('givingupwaitingforrootdevice', 'root device not found'), + ('initramfs', 'stuck in the initramfs'), + ('interactiveshell', 'UEFI shell: nothing to boot'), +) + + +def boot_verdict(img: Image.Image, use_ocr: bool = True, ocr=None) -> tuple[str, str]: + """('pass' | 'fail' | 'wait', detail) for the console of a test-restored VM. Pass: a login prompt, a lock or + sign-in screen, or a shell (auto-login). Fail: a screen that shows the VM is stuck (stop screen, recovery key, + nothing to boot). Anything else (blank, boot logo, log output): wait and look again.""" + ocr = ocr or ocr_lines + if is_blank(img): + return 'wait', 'screen is blank' + if not use_ocr: + return 'wait', 'no OCR available' + try: + lines = ocr(img) + except OCRFailed as e: + return 'wait', str(e) + flat = _letters(' '.join(lines)) + for phrase, what in BOOT_FAIL_PHRASES: + if phrase in flat: + return 'fail', what + found = text_verdict(lines) + if found == 'shell': + return 'pass', 'shell prompt (logged in automatically)' + if found: + return 'pass', found + return 'wait', 'no login screen yet' diff --git a/dashboard/app.py b/dashboard/app.py index 6394417..c5571e1 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -1793,6 +1793,15 @@ def stream(): ('DELETE', r'proxies/(\d+)', 'backup.proxies.manage', ('owner', 'proxy')), ('POST', r'proxies/(\d+)/(update|test|bench)', 'backup.proxies.manage', ('owner', 'proxy')), ('GET', r'proxies/(\d+)/(logs|bench)', 'backup.proxies.manage', ('owner', 'proxy')), + ('GET', r'test-plans', 'backup.view', 'folder'), + ('POST', r'test-plans', 'backup.schedule', 'folder'), + ('PUT', r'test-plans/(\d+)', 'backup.schedule', 'folder'), + ('DELETE', r'test-plans/(\d+)', 'backup.schedule', 'folder'), + ('POST', r'test-plans/(\d+)/run', 'backup.run', 'folder'), + ('POST', r'test-plans/(\d+)/vms', 'backup.schedule', 'vm'), + ('DELETE', r'test-plans/(\d+)/vms', 'backup.schedule', 'folder'), + ('GET', r'test-runs', 'backup.view', 'folder_some'), + ('GET', r'test-runs/(\d+)/screenshot', 'backup.view', ('owner', 'test_run')), ('GET', r'verification', 'backup.view', 'folder'), ('PUT', r'verification', 'backup.schedule', 'folder'), ('GET', r'chains', 'backup.view', 'folder_some'), @@ -1983,7 +1992,7 @@ def _narrow_backup(sub: str, data, scope, cid: str): rows = lambda xs, key='vm_uuid': [x for x in (xs or []) if isinstance(x, dict) and keep(x.get(key))] # noqa: E731 if sub == 'vms': return rows(data, 'uuid') - if sub in ('plans', 'chains', 'restores', 'flr/mounts'): + if sub in ('plans', 'chains', 'restores', 'flr/mounts', 'test-runs'): return rows(data) if sub == 'vmedit/changes': return dict(data, changes=rows(data.get('changes'))) @@ -2079,12 +2088,12 @@ def backup_proxy(sub): payload['created_by'] = user if sub in ('restores', 'flr/mounts') or sub.endswith('/iso'): payload['requested_by'] = user - if sub == 'verification': + if sub == 'verification' or sub.startswith('test-plans'): payload['updated_by'] = user body = json.dumps(payload).encode() headers['Content-Type'] = 'application/json' if request.method == 'GET' and (sub.startswith('flr/mounts/') and sub.rsplit('/', 1)[-1] in ('file', 'zip') - or re.fullmatch(r'proxies/\d+/logs', sub)): + or re.fullmatch(r'proxies/\d+/logs', sub) or re.fullmatch(r'test-runs/\d+/screenshot', sub)): # downloads stream through; nothing in them is a target path or credential try: rq = urllib.request.Request(f'{url}/api/v1/{sub}?{qs}', headers=headers) diff --git a/dashboard/backup_scope.py b/dashboard/backup_scope.py index 85569a9..a4cbc03 100644 --- a/dashboard/backup_scope.py +++ b/dashboard/backup_scope.py @@ -48,7 +48,7 @@ def keep(row, key='vm_uuid', cluster_level=False): def rows(xs, key='vm_uuid', cluster_level=False): return [x for x in (xs or []) if isinstance(x, dict) and keep(x, key, cluster_level)] - if sub in ('plans', 'chains', 'restores', 'flr/mounts'): + if sub in ('plans', 'chains', 'restores', 'flr/mounts', 'test-runs'): return rows(data) if sub in ('runs', 'runs/status'): return dict(data, runs=rows(data.get('runs')), restores=rows(data.get('restores')), diff --git a/dashboard/mail_texts.py b/dashboard/mail_texts.py index 32c406f..69b5d3f 100644 --- a/dashboard/mail_texts.py +++ b/dashboard/mail_texts.py @@ -55,6 +55,10 @@ "DR so its proxies verify around the clock, or check that the proxies are up.\n\n" "HyperCore Manager: {link}\n\n" "You receive this as the closest administrator of this folder.\n"), + 'test_failed': ('HyperCore Manager: test restore failed in {folder}', + '{n} test restore(s) in {folder} failed: the newest backup of these VMs was restored as a test VM and did not come up as it should.\n\n{items}\n\nThe backup may not be usable for a real restore. Look at the screenshot under Backup → Runs → Test restores, fix the cause and run the test again.\n\nHyperCore Manager: {link}\n\nYou receive this as the closest administrator of this folder.\n'), + 'test_overdue': ('HyperCore Manager: VMs in {folder} are not being test-restored', + "{n} VM(s) in a test plan of {folder} have had no passed test restore for twice the plan's interval.\n\n{items}\n\nCheck that the plan is enabled and that its target cluster has room and time for the tests.\n\nHyperCore Manager: {link}\n\nYou receive this as the closest administrator of this folder.\n"), 'test': ("HyperCore Manager: test mail", "This is a test mail from HyperCore Manager, sent by {actor}.\n\n" "If you can read this, mail from HyperCore Manager reaches you.\n"), @@ -104,6 +108,10 @@ "als DR zodat de proxy's daar de klok rond controleren, of kijk of de proxy's draaien.\n\n" "HyperCore Manager: {link}\n\n" "Je ontvangt dit als dichtstbijzijnde beheerder van deze map.\n"), + 'test_failed': ('HyperCore Manager: testherstel mislukt in {folder}', + "{n} testherstel(len) in {folder} mislukt: de nieuwste back-up van deze VM's is als test-VM hersteld en kwam niet op zoals het hoort.\n\n{items}\n\nDe back-up is mogelijk niet bruikbaar voor een echt herstel. Bekijk de schermafbeelding onder Back-up → Runs → Testherstel, los de oorzaak op en test opnieuw.\n\nHyperCore Manager: {link}\n\nJe ontvangt dit als dichtstbijzijnde beheerder van deze map.\n"), + 'test_overdue': ("HyperCore Manager: VM's in {folder} worden niet testhersteld", + "{n} VM('s) in een testplan van {folder} hebben twee keer de interval van het plan geen geslaagd testherstel gehad.\n\n{items}\n\nControleer of het plan aan staat en of het doelcluster ruimte en tijd heeft voor de tests.\n\nHyperCore Manager: {link}\n\nJe ontvangt dit als dichtstbijzijnde beheerder van deze map.\n"), 'test': ("HyperCore Manager: testmail", "Dit is een testmail van HyperCore Manager, verstuurd door {actor}.\n\n" "Als je dit kunt lezen, komt mail van HyperCore Manager bij je aan.\n"), @@ -153,6 +161,10 @@ "Cluster als DR, damit seine Proxys rund um die Uhr prüfen, oder prüfen Sie, ob die Proxys laufen.\n\n" "HyperCore Manager: {link}\n\n" "Sie erhalten dies als nächstgelegener Administrator dieses Ordners.\n"), + 'test_failed': ('HyperCore Manager: Test-Wiederherstellung in {folder} fehlgeschlagen', + '{n} Test-Wiederherstellung(en) in {folder} fehlgeschlagen: das neueste Backup dieser VMs wurde als Test-VM wiederhergestellt und startete nicht wie erwartet.\n\n{items}\n\nDas Backup ist für eine echte Wiederherstellung möglicherweise nicht brauchbar. Sehen Sie sich den Screenshot unter Backup → Läufe → Test-Wiederherstellungen an, beheben Sie die Ursache und testen Sie erneut.\n\nHyperCore Manager: {link}\n\nSie erhalten dies als nächstgelegener Administrator dieses Ordners.\n'), + 'test_overdue': ('HyperCore Manager: VMs in {folder} werden nicht testweise wiederhergestellt', + '{n} VM(s) in einem Testplan von {folder} hatten seit dem doppelten Intervall des Plans keine erfolgreiche Test-Wiederherstellung.\n\n{items}\n\nPrüfen Sie, ob der Plan aktiv ist und ob sein Zielcluster Platz und Zeit für die Tests hat.\n\nHyperCore Manager: {link}\n\nSie erhalten dies als nächstgelegener Administrator dieses Ordners.\n'), 'test': ("HyperCore Manager: Testmail", "Dies ist eine Testmail von HyperCore Manager, gesendet von {actor}.\n\n" "Wenn Sie dies lesen können, erreicht Sie Mail von HyperCore Manager.\n"), @@ -202,6 +214,10 @@ "passif comme PRA pour que ses proxys vérifient en continu, ou vérifiez que les proxys tournent.\n\n" "HyperCore Manager : {link}\n\n" "Vous recevez ce message en tant qu'administrateur le plus proche de ce dossier.\n"), + 'test_failed': ('HyperCore Manager : échec de restauration de test dans {folder}', + "{n} restauration(s) de test dans {folder} ont échoué : la sauvegarde la plus récente de ces VM a été restaurée comme VM de test et n'a pas démarré comme prévu.\n\n{items}\n\nLa sauvegarde n'est peut-être pas utilisable pour une vraie restauration. Consultez la capture d'écran dans Sauvegarde → Exécutions → Restaurations de test, corrigez la cause et relancez le test.\n\nHyperCore Manager : {link}\n\nVous recevez ce message en tant qu'administrateur le plus proche de ce dossier.\n"), + 'test_overdue': ('HyperCore Manager : les VM de {folder} ne sont pas testées par restauration', + "{n} VM d'un plan de test de {folder} n'ont eu aucune restauration de test réussie depuis deux fois l'intervalle du plan.\n\n{items}\n\nVérifiez que le plan est actif et que son cluster cible a la place et le temps pour les tests.\n\nHyperCore Manager : {link}\n\nVous recevez ce message en tant qu'administrateur le plus proche de ce dossier.\n"), 'test': ("HyperCore Manager : e-mail de test", "Ceci est un e-mail de test de HyperCore Manager, envoyé par {actor}.\n\n" "Si vous pouvez lire ceci, les e-mails de HyperCore Manager vous parviennent.\n"), diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 1422095..d616084 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -4822,7 +4822,7 @@

HyperCore Manager

${_clEsc(p.name)}
${_clEsc(p.url)}
${_clEsc(p.cluster_name)} ${_clEsc(p.status === 'updating' ? t('proxies.updating') : (p.status || '—'))}${p.enabled ? '' : ` ${t('ex.paused')}`}
${p.vm_uuid ? t('proxies.vm_detected') : t('proxies.vm_missing')}${p.status_detail ? ' · ' + _clEsc(p.status_detail) : ''}
- ${_clEsc(p.version || '—')}${_pxUpdateCell(p, stackImage)}
${_exFmt(p.last_seen_at)}
+ ${_clEsc(p.version || '—')}${_pxUpdateCell(p, stackImage)}${p.kind !== 'local' && p.capabilities ? `
${t(p.capabilities.host_network ? 'proxies.net_tests_ready' : 'proxies.net_tests_redeploy')}
` : ''}
${_exFmt(p.last_seen_at)}
@@ -4853,6 +4853,7 @@

HyperCore Manager

+
${t('proxies.d_test_vlan_hint')}
@@ -4885,6 +4886,7 @@

HyperCore Manager

mem_gb: parseInt(g('mem').value || '2', 10), disk_gb: parseInt(g('disk').value || '20', 10), ip: g('ipmode').value === 'static' ? {mode: 'static', address: g('ip').value.trim(), prefix: parseInt(g('prefix').value || '24', 10), gateway: g('gw').value.trim(), dns: g('dns').value.trim()} : {mode: 'dhcp'}, image_url: g('image-url').value.trim(), authorized_key: g('key').value.trim() }; + if (g('testvlan') && g('testvlan').value !== '') body.test_vlan = parseInt(g('testvlan').value, 10); if (!body.name) { _shMsg('pxd-msg', t('proxies.d_name_required'), 'err'); return; } if (!await hcmConfirm(t('proxies.deploy_confirm', {name: body.name}))) return; _shMsg('pxd-msg', t('ex.i_starting'), ''); @@ -6189,6 +6191,10 @@

HyperCore Manager

if (it.kind === 'console') return t('alerts.console_open', {vm: _exEsc(it.vm_name || '')}); if (it.kind === 'notice' && it.notice_kind === 'verify_failed') return t('notice.verify_failed', {vm: _exEsc(it.vm_name || '?'), seq: it.seq ?? '?', detail: _exEsc(it.description || '')}); + if (it.kind === 'notice' && it.notice_kind === 'test_failed') + return t('notice.test_failed', {vm: _exEsc(it.vm_name || '?'), detail: _exEsc(it.description || '')}); + if (it.kind === 'notice' && it.notice_kind === 'test_overdue') + return t('notice.test_overdue', {vm: _exEsc(it.vm_name || '?'), detail: _exEsc(it.description || '')}); if (it.kind === 'notice' && it.notice_kind === 'verify_overdue') return t('notice.verify_overdue', {vm: _exEsc(it.vm_name || '?'), detail: _exEsc(it.description || '')}); if (it.kind === 'notice' && it.notice_kind === 'update_terminated') { @@ -6484,8 +6490,8 @@

HyperCore Manager

${rows.length ? rows.map(_polCard).join('') : `
${t('ex.pol_none')}
`} `; }; - await _vfLoad(); - el.innerHTML = `${_exLocationLine(null)}
${scope} ${t('ex.pol_intro')}
` + section('incremental') + _vfSection() + section('export'); + await Promise.all([_vfLoad(), _trLoad()]); + el.innerHTML = `${_exLocationLine(null)}
${scope} ${t('ex.pol_intro')}
` + section('incremental') + _vfSection() + _trSection() + section('export'); if (_polEditing) _polFormInit(_polEditing); if (_polMembersOpen) exPolicyMembers(_polMembersOpen, true); if (_polNightOpen) exPolicyNight(_polNightOpen[0], _polNightOpen[1], true); @@ -6918,7 +6924,9 @@

HyperCore Manager

${kind === 'run' && r.mode ? `${r.mode === 'incremental' ? t(r.point_kind === 'full' ? 'ex.point_full' : 'ex.point_delta') : t('ex.mode_export')} ` : ''}${kind === 'rst' && r.kind === 'files' ? `${t('ex.files')} ` : ''}${r.status === 'RUNNING' ? '' : _exEsc(r.message || '')}${kind === 'rst' && r.kind === 'files' && r.created_uuid && r.status === 'COMPLETE' ? ` ` : ''}${r.task_tag ? `
task ${_exEsc(r.task_tag)}
` : ''} `).join('')}` : `
${t('ex.no_runs')}
`} `; - el.innerHTML = table(t('ex.runs_title'), runs, 'run') + (_exRunsFilter ? '' : table(t('ex.restores_title'), restores, 'rst') + table(t('ex.imports_title'), imports, 'imp') + _vfHistory(d.verifications || [])); + let tests = []; + if (!_exRunsFilter) { try { tests = await _exCall('GET', '/api/backup/test-runs?limit=100'); } catch (e) { tests = []; } } + el.innerHTML = table(t('ex.runs_title'), runs, 'run') + (_exRunsFilter ? '' : _trHistory(tests) + table(t('ex.restores_title'), restores, 'rst') + table(t('ex.imports_title'), imports, 'imp') + _vfHistory(d.verifications || [])); clearTimeout(_exPollTimer); if ([...runs, ...imports, ...restores].some(r => r.status === 'RUNNING')) { // poll while anything runs, but only while this panel is on screen and the cluster unchanged @@ -7005,6 +7013,165 @@

HyperCore Manager

: `
${t('vf.history_none')}
`}`; } +// ── test restores (per folder): plans on the Schedules tab, results on the Runs tab, a column on the +// restore points ───────────────────────────────────────────────────────────────────────────────────── +let _trData = null, _trEditing = null; // _trEditing: null | 'new' | plan id +async function _trLoad() { + try { _trData = await _exCall('GET', '/api/backup/test-plans'); } catch (e) { _trData = null; } +} +const _trDr = () => ((_trData && _trData.proxies) || []).filter(p => p.role === 'dr'); +function _trTargetLine(p) { + const dr = [...new Set(_trDr().map(x => x.cluster_name))]; + return dr.length ? t('tr.target_dr', {names: dr.map(_exEsc).join(', ')}) : t('tr.target_own', {from: _exEsc(p.hours_from), until: _exEsc(p.hours_until)}); +} +function _trSection() { + const d = _trData; + if (!d) return ''; + const head = `
+ ${t('tr.title')} + ${_trEditing === 'new' ? '' : ``}
`; + const body = (d.plans || []).map(p => _trEditing === p.id ? _trForm(p) : _trCard(p)).join(''); + return `
${head} +
${t('tr.intro')}
+ ${_trEditing === 'new' ? _trForm(null) : ''} + ${body || (_trEditing === 'new' ? '' : `
${t('tr.none')}
`)}
`; +} +function _trCard(p) { + const fixed = (p.members || []).filter(m => m.mode === 'fixed'), excl = (p.members || []).filter(m => m.mode === 'exclude'); + const netReady = ((_trData.proxies || []).filter(x => (_trDr().length ? x.role === 'dr' : true) && x.host_network)).length > 0; + const opts = [ + t('tr.timeout', {n: p.timeout_minutes}), + p.keep_failed_hours ? t('tr.keep_on', {n: p.keep_failed_hours}) : t('tr.keep_off'), + p.byte_budget_gb ? t('tr.budget_on', {n: p.byte_budget_gb}) : t('tr.budget_off'), + ]; + if (p.level === 'network') opts.push(t('tr.net_line', {vlan: p.test_vlan, probe: _exEsc(p.probe_address || '?'), ports: (p.default_ports || []).join(', ') || t('tr.ports_ping')})); + const vms = (_trData.vms || []); + const member = m => `${m.mode === 'exclude' ? '✕ ' : ''}${_exEsc(m.vm_name || m.vm_uuid.slice(0, 8))}${m.ports ? ` · ${m.ports.join(',')}` : ''} + ×`; + return `
+
+ ${_exEsc(p.name)} + ${t(p.enabled ? 'tr.enabled' : 'tr.disabled')} + ${t(p.level === 'network' ? 'tr.level_network' : 'tr.level_boot')} + ${p.level === 'network' && !netReady ? `${t('tr.net_not_ready')}` : ''} + + + +
+
${t('tr.rule', {n: p.interval_days, fixed: fixed.length, random: p.random_count, weeks: p.rest_weeks})} ${_trTargetLine(p)}
+
${opts.join(' · ')}${p.last_run_at ? ` · ${t('tr.last_round', {when: _exFmt(p.last_run_at)})}` : ''}
+
${fixed.map(member).join('')}${excl.map(member).join('')}
+
+ + + ${p.level === 'network' ? `` : ''} + +
+
`; +} +function _trForm(p) { + const v = p || {name: '', enabled: true, interval_days: 7, random_count: 2, rest_weeks: 4, level: 'boot', test_vlan: null, probe_address: '', + default_ports: [], timeout_minutes: 10, keep_failed_hours: null, byte_budget_gb: null, hours_from: '01:00', hours_until: '06:00'}; + const id = p ? p.id : 'new'; + return `
+
+
+
+
+ ${t('tr.f_rest')}
+
${t('tr.f_random_hint')}
+
+
${t('tr.f_level_hint')}
+
+
+
+
+
${t('tr.f_net_hint')}
+
+
–
+
${t('tr.f_hours_hint')}
+
+
${t('tr.f_hours_unit')}
+
+
GB
+
${t('tr.f_budget_hint')}
+
+
+
+
+
`; +} +async function trSave(id) { + const g = k => document.getElementById('trf-' + k); + const level = g('level').value; + const body = {name: g('name').value.trim(), enabled: g('enabled').checked, interval_days: parseInt(g('interval').value, 10), + random_count: parseInt(g('random').value || '0', 10), rest_weeks: parseInt(g('rest').value || '4', 10), level, + timeout_minutes: parseInt(g('timeout').value || '10', 10), hours_from: g('from').value, hours_until: g('until').value, + keep_failed_hours: g('keep-on').checked ? parseInt(g('keep').value, 10) : null, + byte_budget_gb: g('budget-on').checked ? parseInt(g('budget').value, 10) : null}; + if (level === 'network') Object.assign(body, {test_vlan: g('vlan').value === '' ? null : parseInt(g('vlan').value, 10), + probe_address: g('probe').value.trim(), default_ports: g('ports').value}); + try { + if (id === 'new') await _exCall('POST', '/api/backup/test-plans', body); + else await _exCall('PUT', `/api/backup/test-plans/${id}`, body); + _trEditing = null; exLoadPolicies(); + } catch (e) { _shMsg('trf-msg', e.message, 'err'); } +} +async function trDelete(id, name) { + if (!await hcmConfirm(t('tr.confirm_delete', {name}), {danger: true})) return; + try { await _exCall('DELETE', `/api/backup/test-plans/${id}`); exLoadPolicies(); } catch (e) { showToast(e.message, 'err'); } +} +async function trRun(id) { + try { const r = await _exCall('POST', `/api/backup/test-plans/${id}/run`); showToast(t('tr.queued', {n: r.queued}), 'ok'); } + catch (e) { showToast(e.message, 'err'); } +} +async function trVmAdd(id) { + const [cid, vm, name] = document.getElementById(`tr-${id}-vm`).value.split('|'); + const body = {cluster_id: cid, vm_uuid: vm, vm_name: name, mode: document.getElementById(`tr-${id}-mode`).value}; + const ports = document.getElementById(`tr-${id}-ports`); + if (ports && ports.value.trim()) body.ports = ports.value; + try { await _exCall('POST', `/api/backup/test-plans/${id}/vms`, body); exLoadPolicies(); } catch (e) { _shMsg(`tr-${id}-msg`, e.message, 'err'); } +} +async function trVmRemove(id, cid, vm) { + try { await _exCall('DELETE', `/api/backup/test-plans/${id}/vms?cluster_id=${encodeURIComponent(cid)}&vm_uuid=${encodeURIComponent(vm)}`); exLoadPolicies(); } + catch (e) { showToast(e.message, 'err'); } +} +function _trStatusBadge(r) { + const cls = {passed: 'ok', failed: 'err', running: 'run', queued: 'off', skipped: 'warn', error: 'warn'}[r.status] || 'off'; + return `${t('tr.status_' + r.status)}`; +} +function _trHistory(rows) { + const ago = iso => iso ? Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 3600000)) : null; + const dur = (a, b) => a && b ? _polDur((new Date(b) - new Date(a)) / 1000) : ''; + return `
+
${t('tr.history_title')}
+ ${rows.length ? ` + ${rows.map(r => ` + + + + `).join('')}
${t('ex.col_vm')}${t('ex.col_started')}${t('ex.col_status')}${t('ex.col_detail')}
${_exEsc(r.vm_name || '?')}${_exClusterHint(r)}
${_exEsc(r.plan_name || '')}${r.picked === 'random' ? ' · ' + t('tr.picked_random') : ''}
${_exFmt(r.started_at || r.queued_at)}${_trStatusBadge(r)}${r.verdict === 'agent' ? ` ${t('tr.v_agent')}` : r.verdict === 'screen' ? ` ${t('tr.v_screen')}` : ''} + ${r.agent === 'unavailable' ? `
${t('tr.agentless')}
` : r.agent === 'unknown' ? `
${t('tr.agent_unknown')}
` : ''}
+ ${r.target_cluster_name ? t('tr.on_cluster', {cluster: _exEsc(r.target_cluster_name)}) : ''}${r.point_created_at ? ` · ${t('tr.point_age', {h: ago(r.point_created_at)})}` : ''}${r.bytes ? ` · ${_exMiB(Math.round(r.bytes / 1048576))}` : ''}${r.restored_at ? ` · ${t('tr.restore_took', {d: dur(r.started_at, r.restored_at)})}` : ''}${r.booted_at ? ` · ${t('tr.boot_took', {d: dur(r.restored_at, r.booted_at)})}` : ''} + ${r.detail ? `
${_exEsc(r.detail)}
` : ''} + ${(r.checks || []).length ? `
${r.checks.map(c => `${_exEsc(c.ip)}: ${t(c.ping ? 'tr.ping_ok' : 'tr.ping_no')}${Object.entries(c.ports || {}).map(([pt, ok]) => ` · ${pt} ${ok ? '✓' : '✕'}`).join('')}`).join('
')}
` : ''} + ${r.keep_until && !r.cleaned_at ? `
${t('tr.kept_until', {when: _exFmt(r.keep_until)})}
` : ''} + ${r.has_screenshot ? `` : ''}
` + : `
${t('tr.history_none')}
`}
`; +} +function trScreenshot(id, vm) { + hcmModal({title: `${_exEsc(vm)} · ${_exEsc(t('tr.screenshot'))}`, width: 'min(1100px, 96vw)', + body: ``, + buttons: [{label: t('acc.close'), onClick: h => h.close()}]}); +} +function _trChainCell(c) { + const lt = c.last_test; + if (!lt) return '—'; + return lt.status === 'passed' ? `${t('tr.chain_passed', {when: _exFmt(lt.finished_at)})}` + : `${t('tr.chain_failed', {when: _exFmt(lt.finished_at)})}`; +} + // ── restore points ────────────────────────────────────────────────────────── const _exMiB = n => n == null ? '—' : (n >= 1024 ? (n / 1024).toFixed(1) + ' GiB' : n + ' MiB'); async function exLoadPoints() { @@ -7016,7 +7183,7 @@

HyperCore Manager

if (!chains.length) { el.innerHTML = `
${t('ex.no_points')}
`; return; } const admin = _exIsAdmin(); el.innerHTML = `
${t('ex.points_title')}
- +
${t('ex.col_vm')}${t('ex.col_status')}${t('ex.col_destination')}${t('ex.col_points')}${t('ex.col_last_point')}${t('ex.col_verified')}
${chains.map(c => ` @@ -7025,6 +7192,7 @@

HyperCore Manager

+ ${rows.map(r => ` - + `).join('')}
${t('ex.col_vm')}${t('ex.col_status')}${t('ex.col_destination')}${t('ex.col_points')}${t('ex.col_last_point')}${t('ex.col_verified')}${t('tr.col_tested')}
${_exEsc(c.vm_name)}${_exClusterHint(c)}
${_exEsc(c.vm_uuid.slice(0, 8))}
${c.point_count} ${_exFmt(c.last_point_at)} ${_vfChainCell(c)}${_trChainCell(c)} ${admin ? ` diff --git a/dashboard/static/lang/de.js b/dashboard/static/lang/de.js index 5da4633..633bba8 100644 --- a/dashboard/static/lang/de.js +++ b/dashboard/static/lang/de.js @@ -1716,4 +1716,84 @@ window.LANG = { 'vf.on_proxy': "auf {proxy}", 'notice.verify_failed': "Backup von {vm}, Punkt #{seq}, stimmt nicht mehr mit seinen Prüfsummen überein: {detail}. Wiederherstellungen aus diesem und späteren Punkten der Kette ist nicht zu trauen; erstellen Sie ein neues Vollbackup.", 'notice.verify_overdue': "Backups von {vm} werden nicht geprüft: {detail}.", + + // test restores (plans/PLAN-test-restores.md) + 'proxies.d_test_vlan': "Test-VLAN (optional)", + 'proxies.d_test_vlan_hint': "Eine zweite NIC in einem isolierten VLAN, für die Netzwerkprüfungen von Test-Wiederherstellungen.", + 'proxies.net_tests_ready': "kann Netzwerktests ausführen", + 'proxies.net_tests_redeploy': "Netzwerktests: neu bereitstellen (1.7.0+)", + 'tr.title': "Test-Wiederherstellungen", + 'tr.new': "Neuer Testplan", + 'tr.intro': "Eine Test-Wiederherstellung stellt das neueste Backup einer VM als temporäre VM wieder her, startet sie und prüft, ob sie hochkommt: der Guest-Agent antwortet oder die Konsole zeigt einen Anmeldebildschirm. Auf Netzwerkebene hängen ihre NICs in einem isolierten Test-VLAN und der Proxy prüft ihre Ports. Die Test-VM wird danach gelöscht.", + 'tr.none': "Noch keine Testpläne.", + 'tr.enabled': "Aktiv", + 'tr.disabled': "Inaktiv", + 'tr.level_boot': "Starttest (ohne Netzwerk)", + 'tr.level_network': "Netzwerktest (Test-VLAN)", + 'tr.net_not_ready': "kein Proxy kann das Netzwerk testen", + 'tr.net_not_ready_hint': "Netzwerktests brauchen auf dem Zielcluster einen ab 1.7.0 bereitgestellten Proxy mit einer NIC im Test-VLAN (Proxys → Bereitstellen, Test-VLAN).", + 'tr.run_now': "Jetzt ausführen", + 'tr.rule': "Alle {n} Tag(e): {fixed} feste VM(s) plus {random} zufällig (eine getestete VM ruht {weeks} Woche(n)).", + 'tr.target_dr': "Tests laufen auf dem DR-Cluster {names}, zu jeder Stunde (pausiert, solange Backups des Ordners laufen).", + 'tr.target_own': "Kein DR-Cluster in diesem Ordner: Tests laufen auf dem Cluster der jeweiligen VM zwischen {from} und {until}, außerhalb von Backups.", + 'tr.timeout': "Zeitlimit {n} min", + 'tr.keep_on': "fehlgeschlagene VMs {n} h behalten", + 'tr.keep_off': "fehlgeschlagene VMs sofort gelöscht", + 'tr.budget_on': "höchstens {n} GB pro Runde", + 'tr.budget_off': "kein Byte-Budget", + 'tr.net_line': "VLAN {vlan}, Probe {probe}, Ports {ports}", + 'tr.ports_ping': "keine (Ping)", + 'tr.last_round': "letzte Runde {when}", + 'tr.remove_vm': "Aus dem Plan entfernen", + 'tr.mode_fixed': "immer testen", + 'tr.mode_exclude': "nie testen", + 'tr.ports_vm_ph': "Ports dieser VM", + 'tr.add_vm': "Hinzufügen", + 'tr.f_name': "Name", + 'tr.f_interval': "Eine Runde alle (Tage)", + 'tr.f_random': "Zufällige VMs pro Runde", + 'tr.f_rest': "Ruhe (Wochen)", + 'tr.f_random_hint': "Aus den gesicherten VMs des Ordners gewählt, am längsten ungetestete zuerst; feste und ausgeschlossene VMs fügen Sie auf der Plankarte hinzu.", + 'tr.f_level': "Ebene", + 'tr.f_level_hint': "Start: NICs getrennt. Netzwerk: NICs im Test-VLAN, dann Ping- und Portprüfungen vom Proxy.", + 'tr.f_vlan': "Test-VLAN", + 'tr.f_probe': "Proxy-Adresse im Test-VLAN", + 'tr.f_ports': "Zu prüfende Ports (Standard)", + 'tr.f_net_hint': "Wiederhergestellte VMs behalten Adressen und Namen, daher muss das Test-VLAN isoliert sein: HCM lehnt ein VLAN ab, das eine andere VM auf dem Zielcluster nutzt, kann aber nicht sehen, ob es anderswo geroutet wird. Die Probe-Adresse ist eine freie Adresse im Subnetz der VMs (mit Präfix), die der Proxy während der Prüfungen nutzt. Ohne Ports zählt nur Ping (Windows antwortet standardmäßig nicht auf Ping).", + 'tr.f_timeout': "Lebenszeichen innerhalb (Minuten)", + 'tr.f_hours': "Zeiten auf einem Produktionscluster", + 'tr.f_hours_hint': "Nur genutzt, wenn der Ordner keinen DR-Cluster hat; in der Zeitzone des jeweiligen Clusters.", + 'tr.f_keep': "Fehlgeschlagene Test-VM zur Prüfung behalten", + 'tr.f_hours_unit': "Stunden", + 'tr.f_budget': "Byte-Budget pro Runde", + 'tr.f_budget_hint': "Jeder Test schreibt die ganze VM; Tests, die das Budget überschreiten würden, werden in dieser Runde übersprungen.", + 'tr.confirm_delete': "Testplan '{name}' löschen? Die Ergebnisse bleiben im Verlauf.", + 'tr.queued': "{n} Test(s) eingereiht; sie starten, sobald der Zielcluster sie nehmen darf.", + 'tr.history_title': "Test-Wiederherstellungen", + 'tr.history_none': "Noch keine Test-Wiederherstellung gelaufen.", + 'tr.picked_random': "zufällig gewählt", + 'tr.v_agent': "per Agent", + 'tr.v_screen': "per Bildschirm", + 'tr.agentless': "ohne Agent: nur Bildschirmprüfung", + 'tr.agentless_hint': "Die VM hat in Produktion keinen Guest-Agent, ein Erfolg beruht also nur auf dem Konsolenbild (eine schwächere Prüfung).", + 'tr.agent_unknown': "Agent unbekannt (VM aus)", + 'tr.on_cluster': "auf {cluster}", + 'tr.point_age': "Punkt {h} h alt", + 'tr.restore_took': "Wiederherstellung {d}", + 'tr.boot_took': "Start {d}", + 'tr.ping_ok': "Ping ✓", + 'tr.ping_no': "kein Ping", + 'tr.kept_until': "Test-VM behalten bis {when}", + 'tr.screenshot': "Screenshot", + 'tr.status_queued': "Eingereiht", + 'tr.status_running': "Läuft", + 'tr.status_passed': "Bestanden", + 'tr.status_failed': "Fehlgeschlagen", + 'tr.status_skipped': "Übersprungen", + 'tr.status_error': "Nicht getestet", + 'tr.col_tested': "Getestet", + 'tr.chain_passed': "gestartet {when}", + 'tr.chain_failed': "fehlgeschlagen {when}", + 'notice.test_failed': "Test-Wiederherstellung von {vm} fehlgeschlagen: {detail}. Das Backup ist für eine echte Wiederherstellung möglicherweise nicht brauchbar.", + 'notice.test_overdue': "{vm} wird nicht testweise wiederhergestellt: {detail}.", }; diff --git a/dashboard/static/lang/en.js b/dashboard/static/lang/en.js index 325dd6d..1c48bd6 100644 --- a/dashboard/static/lang/en.js +++ b/dashboard/static/lang/en.js @@ -1717,4 +1717,84 @@ window.LANG = { 'vf.on_proxy': "on {proxy}", 'notice.verify_failed': "Backup of {vm}, point #{seq}, no longer matches its checksums: {detail}. Restores from this point and later points of its chain cannot be trusted; make a new full backup.", 'notice.verify_overdue': "Backups of {vm} are not being verified: {detail}.", + + // test restores (plans/PLAN-test-restores.md) + 'proxies.d_test_vlan': "Test VLAN (optional)", + 'proxies.d_test_vlan_hint': "A second NIC on an isolated VLAN, for the network checks of test restores.", + 'proxies.net_tests_ready': "can run network tests", + 'proxies.net_tests_redeploy': "network tests: redeploy (1.7.0+)", + 'tr.title': "Test restores", + 'tr.new': "New test plan", + 'tr.intro': "A test restore restores the newest backup of a VM as a temporary VM, starts it and checks that it comes up: the guest agent answers, or the console shows a login screen. On the network level its NICs are on an isolated test VLAN and the proxy checks its ports. The test VM is deleted afterwards.", + 'tr.none': "No test plans yet.", + 'tr.enabled': "Enabled", + 'tr.disabled': "Disabled", + 'tr.level_boot': "Boot test (no network)", + 'tr.level_network': "Network test (test VLAN)", + 'tr.net_not_ready': "no proxy can test the network", + 'tr.net_not_ready_hint': "Network tests need a proxy on the target cluster deployed with 1.7.0 or later and a NIC on the test VLAN (Proxies → Deploy, Test VLAN).", + 'tr.run_now': "Run now", + 'tr.rule': "Every {n} day(s): {fixed} fixed VM(s) plus {random} at random (a tested VM rests {weeks} week(s)).", + 'tr.target_dr': "Tests run on the DR cluster {names}, at any hour (paused while backups of the folder run).", + 'tr.target_own': "No DR cluster in this folder: tests run on each VM's own cluster between {from} and {until}, outside backups.", + 'tr.timeout': "timeout {n} min", + 'tr.keep_on': "failed VMs kept {n} h", + 'tr.keep_off': "failed VMs deleted at once", + 'tr.budget_on': "at most {n} GB per round", + 'tr.budget_off': "no byte budget", + 'tr.net_line': "VLAN {vlan}, probe {probe}, ports {ports}", + 'tr.ports_ping': "none (ping)", + 'tr.last_round': "last round {when}", + 'tr.remove_vm': "Remove from the plan", + 'tr.mode_fixed': "always test", + 'tr.mode_exclude': "never test", + 'tr.ports_vm_ph': "ports of this VM", + 'tr.add_vm': "Add", + 'tr.f_name': "Name", + 'tr.f_interval': "A round every (days)", + 'tr.f_random': "Random VMs per round", + 'tr.f_rest': "rest (weeks)", + 'tr.f_random_hint': "Picked from the folder's backed-up VMs, longest untested first; fixed and excluded VMs are added on the plan card.", + 'tr.f_level': "Level", + 'tr.f_level_hint': "Boot: NICs disconnected. Network: NICs on the test VLAN, then ping and port checks from the proxy.", + 'tr.f_vlan': "Test VLAN", + 'tr.f_probe': "Proxy address on the test VLAN", + 'tr.f_ports': "Ports to check (default)", + 'tr.f_net_hint': "Restored VMs keep their addresses and names, so the test VLAN must be isolated: HCM refuses a VLAN that another VM on the target cluster uses, but cannot see whether it is routed elsewhere. The probe address is a free address in the VMs' subnet (with prefix) that the proxy uses during the checks. Without ports only ping counts (Windows answers no ping by default).", + 'tr.f_timeout': "Sign of life within (minutes)", + 'tr.f_hours': "Hours on a production cluster", + 'tr.f_hours_hint': "Only used when the folder has no DR cluster; in each cluster's own time zone.", + 'tr.f_keep': "Keep a failed test VM for inspection", + 'tr.f_hours_unit': "hours", + 'tr.f_budget': "Byte budget per round", + 'tr.f_budget_hint': "Each test writes the whole VM; tests that would pass the budget are skipped in that round.", + 'tr.confirm_delete': "Delete the test plan '{name}'? Its results stay in the history.", + 'tr.queued': "{n} test(s) queued; they start when the target cluster may take them.", + 'tr.history_title': "Test restores", + 'tr.history_none': "No test restore has run yet.", + 'tr.picked_random': "picked at random", + 'tr.v_agent': "by agent", + 'tr.v_screen': "by screen", + 'tr.agentless': "agentless: screen check only", + 'tr.agentless_hint': "The VM has no guest agent in production, so a pass rests on the console screen alone (a weaker check).", + 'tr.agent_unknown': "agent unknown (VM is off)", + 'tr.on_cluster': "on {cluster}", + 'tr.point_age': "point {h} h old", + 'tr.restore_took': "restore {d}", + 'tr.boot_took': "boot {d}", + 'tr.ping_ok': "ping ✓", + 'tr.ping_no': "no ping", + 'tr.kept_until': "test VM kept until {when}", + 'tr.screenshot': "Screenshot", + 'tr.status_queued': "Queued", + 'tr.status_running': "Running", + 'tr.status_passed': "Passed", + 'tr.status_failed': "Failed", + 'tr.status_skipped': "Skipped", + 'tr.status_error': "Not tested", + 'tr.col_tested': "Tested", + 'tr.chain_passed': "booted {when}", + 'tr.chain_failed': "failed {when}", + 'notice.test_failed': "Test restore of {vm} failed: {detail}. The backup may not be usable for a real restore.", + 'notice.test_overdue': "{vm} is not being test-restored: {detail}.", }; diff --git a/dashboard/static/lang/fr.js b/dashboard/static/lang/fr.js index 98c0316..7cac319 100644 --- a/dashboard/static/lang/fr.js +++ b/dashboard/static/lang/fr.js @@ -1716,4 +1716,84 @@ window.LANG = { 'vf.on_proxy': "sur {proxy}", 'notice.verify_failed': "La sauvegarde de {vm}, point n°{seq}, ne correspond plus à ses sommes de contrôle : {detail}. Une restauration depuis ce point ou les suivants de la chaîne n'est pas fiable ; faites une nouvelle sauvegarde complète.", 'notice.verify_overdue': "Les sauvegardes de {vm} ne sont pas vérifiées : {detail}.", + + // test restores (plans/PLAN-test-restores.md) + 'proxies.d_test_vlan': "VLAN de test (facultatif)", + 'proxies.d_test_vlan_hint': "Une seconde carte réseau sur un VLAN isolé, pour les contrôles réseau des restaurations de test.", + 'proxies.net_tests_ready': "peut faire les tests réseau", + 'proxies.net_tests_redeploy': "tests réseau : redéployer (1.7.0+)", + 'tr.title': "Restaurations de test", + 'tr.new': "Nouveau plan de test", + 'tr.intro': "Une restauration de test restaure la sauvegarde la plus récente d'une VM comme VM temporaire, la démarre et vérifie qu'elle démarre : l'agent invité répond, ou la console montre un écran de connexion. Au niveau réseau ses cartes sont sur un VLAN de test isolé et le proxy vérifie ses ports. La VM de test est ensuite supprimée.", + 'tr.none': "Pas encore de plan de test.", + 'tr.enabled': "Actif", + 'tr.disabled': "Inactif", + 'tr.level_boot': "Test de démarrage (sans réseau)", + 'tr.level_network': "Test réseau (VLAN de test)", + 'tr.net_not_ready': "aucun proxy ne peut tester le réseau", + 'tr.net_not_ready_hint': "Les tests réseau demandent sur le cluster cible un proxy déployé en 1.7.0 ou plus avec une carte sur le VLAN de test (Proxys → Déployer, VLAN de test).", + 'tr.run_now': "Lancer maintenant", + 'tr.rule': "Tous les {n} jour(s) : {fixed} VM fixe(s) plus {random} au hasard (une VM testée attend {weeks} semaine(s)).", + 'tr.target_dr': "Les tests tournent sur le cluster PRA {names}, à toute heure (en pause pendant les sauvegardes du dossier).", + 'tr.target_own': "Pas de cluster PRA dans ce dossier : les tests tournent sur le cluster de chaque VM entre {from} et {until}, hors sauvegardes.", + 'tr.timeout': "délai {n} min", + 'tr.keep_on': "VM en échec gardées {n} h", + 'tr.keep_off': "VM en échec supprimées aussitôt", + 'tr.budget_on': "au plus {n} Go par tour", + 'tr.budget_off': "pas de budget d'octets", + 'tr.net_line': "VLAN {vlan}, sonde {probe}, ports {ports}", + 'tr.ports_ping': "aucun (ping)", + 'tr.last_round': "dernier tour {when}", + 'tr.remove_vm': "Retirer du plan", + 'tr.mode_fixed': "toujours tester", + 'tr.mode_exclude': "ne jamais tester", + 'tr.ports_vm_ph': "ports de cette VM", + 'tr.add_vm': "Ajouter", + 'tr.f_name': "Nom", + 'tr.f_interval': "Un tour tous les (jours)", + 'tr.f_random': "VM au hasard par tour", + 'tr.f_rest': "repos (semaines)", + 'tr.f_random_hint': "Choisies parmi les VM sauvegardées du dossier, les plus longtemps non testées d'abord ; les VM fixes et exclues s'ajoutent sur la carte du plan.", + 'tr.f_level': "Niveau", + 'tr.f_level_hint': "Démarrage : cartes déconnectées. Réseau : cartes sur le VLAN de test, puis ping et ports vérifiés depuis le proxy.", + 'tr.f_vlan': "VLAN de test", + 'tr.f_probe': "Adresse du proxy sur le VLAN de test", + 'tr.f_ports': "Ports à vérifier (par défaut)", + 'tr.f_net_hint': "Les VM restaurées gardent leurs adresses et noms, le VLAN de test doit donc être isolé : HCM refuse un VLAN utilisé par une autre VM du cluster cible, mais ne peut pas voir s'il est routé ailleurs. L'adresse de sonde est une adresse libre du sous-réseau des VM (avec préfixe) que le proxy utilise pendant les contrôles. Sans ports seul le ping compte (Windows ne répond pas au ping par défaut).", + 'tr.f_timeout': "Signe de vie sous (minutes)", + 'tr.f_hours': "Heures sur un cluster de production", + 'tr.f_hours_hint': "Utilisé seulement si le dossier n'a pas de cluster PRA ; dans le fuseau de chaque cluster.", + 'tr.f_keep': "Garder une VM de test en échec pour examen", + 'tr.f_hours_unit': "heures", + 'tr.f_budget': "Budget d'octets par tour", + 'tr.f_budget_hint': "Chaque test écrit toute la VM ; les tests qui dépasseraient le budget sont sautés pour ce tour.", + 'tr.confirm_delete': "Supprimer le plan de test « {name} » ? Ses résultats restent dans l'historique.", + 'tr.queued': "{n} test(s) en file ; ils démarrent dès que le cluster cible peut les prendre.", + 'tr.history_title': "Restaurations de test", + 'tr.history_none': "Aucune restauration de test n'a encore tourné.", + 'tr.picked_random': "choisie au hasard", + 'tr.v_agent': "par l'agent", + 'tr.v_screen': "par l'écran", + 'tr.agentless': "sans agent : contrôle d'écran seul", + 'tr.agentless_hint': "La VM n'a pas d'agent invité en production : une réussite repose sur le seul écran de console (contrôle plus faible).", + 'tr.agent_unknown': "agent inconnu (VM éteinte)", + 'tr.on_cluster': "sur {cluster}", + 'tr.point_age': "point de {h} h", + 'tr.restore_took': "restauration {d}", + 'tr.boot_took': "démarrage {d}", + 'tr.ping_ok': "ping ✓", + 'tr.ping_no': "pas de ping", + 'tr.kept_until': "VM de test gardée jusqu'au {when}", + 'tr.screenshot': "Capture d'écran", + 'tr.status_queued': "En file", + 'tr.status_running': "En cours", + 'tr.status_passed': "Réussi", + 'tr.status_failed': "Échoué", + 'tr.status_skipped': "Sauté", + 'tr.status_error': "Non testé", + 'tr.col_tested': "Testé", + 'tr.chain_passed': "démarré {when}", + 'tr.chain_failed': "échoué {when}", + 'notice.test_failed': "Restauration de test de {vm} échouée : {detail}. La sauvegarde n'est peut-être pas utilisable pour une vraie restauration.", + 'notice.test_overdue': "{vm} n'est pas testée par restauration : {detail}.", }; diff --git a/dashboard/static/lang/nl.js b/dashboard/static/lang/nl.js index b577671..002e1b7 100644 --- a/dashboard/static/lang/nl.js +++ b/dashboard/static/lang/nl.js @@ -1716,4 +1716,84 @@ window.LANG = { 'vf.on_proxy': "op {proxy}", 'notice.verify_failed': "Back-up van {vm}, punt #{seq}, komt niet meer overeen met zijn controlesommen: {detail}. Een herstel van dit punt en latere punten van de keten is niet betrouwbaar; maak een nieuwe volledige back-up.", 'notice.verify_overdue': "Back-ups van {vm} worden niet gecontroleerd: {detail}.", + + // test restores (plans/PLAN-test-restores.md) + 'proxies.d_test_vlan': "Test-VLAN (optioneel)", + 'proxies.d_test_vlan_hint': "Een tweede NIC op een geïsoleerd VLAN, voor de netwerkcontroles van testherstel.", + 'proxies.net_tests_ready': "kan netwerktests doen", + 'proxies.net_tests_redeploy': "netwerktests: opnieuw uitrollen (1.7.0+)", + 'tr.title': "Testherstel", + 'tr.new': "Nieuw testplan", + 'tr.intro': "Een testherstel zet de nieuwste back-up van een VM terug als tijdelijke VM, start die en controleert of hij opkomt: de guest agent antwoordt, of de console toont een aanmeldscherm. Op netwerkniveau zitten de NIC's op een geïsoleerd test-VLAN en controleert de proxy de poorten. De test-VM wordt daarna verwijderd.", + 'tr.none': "Nog geen testplannen.", + 'tr.enabled': "Aan", + 'tr.disabled': "Uit", + 'tr.level_boot': "Opstarttest (geen netwerk)", + 'tr.level_network': "Netwerktest (test-VLAN)", + 'tr.net_not_ready': "geen proxy kan het netwerk testen", + 'tr.net_not_ready_hint': "Netwerktests hebben een proxy op het doelcluster nodig, uitgerold met 1.7.0 of later en met een NIC op het test-VLAN (Proxy's → Uitrollen, Test-VLAN).", + 'tr.run_now': "Nu uitvoeren", + 'tr.rule': "Elke {n} dag(en): {fixed} vaste VM('s) plus {random} willekeurig (een geteste VM rust {weeks} week/weken).", + 'tr.target_dr': "Tests draaien op het DR-cluster {names}, op elk uur (gepauzeerd zolang back-ups van de map lopen).", + 'tr.target_own': "Geen DR-cluster in deze map: tests draaien op het eigen cluster van elke VM tussen {from} en {until}, buiten back-ups om.", + 'tr.timeout': "time-out {n} min", + 'tr.keep_on': "mislukte VM's {n} u bewaard", + 'tr.keep_off': "mislukte VM's meteen verwijderd", + 'tr.budget_on': "hoogstens {n} GB per ronde", + 'tr.budget_off': "geen bytebudget", + 'tr.net_line': "VLAN {vlan}, probe {probe}, poorten {ports}", + 'tr.ports_ping': "geen (ping)", + 'tr.last_round': "laatste ronde {when}", + 'tr.remove_vm': "Uit het plan halen", + 'tr.mode_fixed': "altijd testen", + 'tr.mode_exclude': "nooit testen", + 'tr.ports_vm_ph': "poorten van deze VM", + 'tr.add_vm': "Toevoegen", + 'tr.f_name': "Naam", + 'tr.f_interval': "Een ronde elke (dagen)", + 'tr.f_random': "Willekeurige VM's per ronde", + 'tr.f_rest': "rust (weken)", + 'tr.f_random_hint': "Gekozen uit de geback-upte VM's van de map, langst ongetest eerst; vaste en uitgesloten VM's voeg je toe op de plankaart.", + 'tr.f_level': "Niveau", + 'tr.f_level_hint': "Opstart: NIC's losgekoppeld. Netwerk: NIC's op het test-VLAN, daarna ping- en poortcontroles vanaf de proxy.", + 'tr.f_vlan': "Test-VLAN", + 'tr.f_probe': "Proxyadres op het test-VLAN", + 'tr.f_ports': "Te controleren poorten (standaard)", + 'tr.f_net_hint': "Herstelde VM's houden hun adressen en namen, dus het test-VLAN moet geïsoleerd zijn: HCM weigert een VLAN dat een andere VM op het doelcluster gebruikt, maar kan niet zien of het elders gerouteerd wordt. Het probe-adres is een vrij adres in het subnet van de VM's (met prefix) dat de proxy tijdens de controles gebruikt. Zonder poorten telt alleen ping (Windows antwoordt standaard niet op ping).", + 'tr.f_timeout': "Teken van leven binnen (minuten)", + 'tr.f_hours': "Uren op een productiecluster", + 'tr.f_hours_hint': "Alleen gebruikt als de map geen DR-cluster heeft; in de tijdzone van elk cluster.", + 'tr.f_keep': "Mislukte test-VM bewaren om te bekijken", + 'tr.f_hours_unit': "uur", + 'tr.f_budget': "Bytebudget per ronde", + 'tr.f_budget_hint': "Elke test schrijft de hele VM; tests die het budget zouden overschrijden worden in die ronde overgeslagen.", + 'tr.confirm_delete': "Testplan '{name}' verwijderen? De resultaten blijven in de geschiedenis.", + 'tr.queued': "{n} test(s) in de wachtrij; ze starten zodra het doelcluster ze mag nemen.", + 'tr.history_title': "Testherstel", + 'tr.history_none': "Er is nog geen testherstel gedraaid.", + 'tr.picked_random': "willekeurig gekozen", + 'tr.v_agent': "via agent", + 'tr.v_screen': "via scherm", + 'tr.agentless': "zonder agent: alleen schermcontrole", + 'tr.agentless_hint': "De VM heeft in productie geen guest agent, dus een geslaagde test rust alleen op het consolescherm (een zwakkere controle).", + 'tr.agent_unknown': "agent onbekend (VM staat uit)", + 'tr.on_cluster': "op {cluster}", + 'tr.point_age': "punt {h} u oud", + 'tr.restore_took': "herstel {d}", + 'tr.boot_took': "opstart {d}", + 'tr.ping_ok': "ping ✓", + 'tr.ping_no': "geen ping", + 'tr.kept_until': "test-VM bewaard tot {when}", + 'tr.screenshot': "Schermafbeelding", + 'tr.status_queued': "In wachtrij", + 'tr.status_running': "Bezig", + 'tr.status_passed': "Geslaagd", + 'tr.status_failed': "Mislukt", + 'tr.status_skipped': "Overgeslagen", + 'tr.status_error': "Niet getest", + 'tr.col_tested': "Getest", + 'tr.chain_passed': "opgestart {when}", + 'tr.chain_failed': "mislukt {when}", + 'notice.test_failed': "Testherstel van {vm} mislukt: {detail}. De back-up is mogelijk niet bruikbaar voor een echt herstel.", + 'notice.test_overdue': "{vm} wordt niet testhersteld: {detail}.", }; diff --git a/dashboard/verify_mail.py b/dashboard/verify_mail.py index 4a6cdd1..5ff2d47 100644 --- a/dashboard/verify_mail.py +++ b/dashboard/verify_mail.py @@ -1,8 +1,9 @@ """ verify_mail.py — mails about failed and overdue backup verifications (plans/PLAN-chain-verify.md). -The backup service records each new failure (and each chain not verified for twice its folder's interval) -as a row in backup.verify_alerts. It has no idea who the people are: that is the dashboard's tenant tree. +The backup service records each new failure (and each chain not verified for twice its folder's interval, +each failed test restore, each tested VM without a passed test for twice its plan's interval) as a row in +backup.verify_alerts. It has no idea who the people are: that is the dashboard's tenant tree. So a thread here (one per gunicorn worker; a row is claimed atomically, so it is mailed once) collects the new rows every minute, waits two minutes so a burst becomes one mail, and mails them per folder to the **closest admin**: whoever holds the Admin role nearest the folder, so the folder's own admins, else the @@ -99,7 +100,8 @@ def line(a: dict, clusters: dict) -> str: def compose(rows: list[dict], folder_name: str, clusters: dict, link: str, lang: str = 'en') -> list[tuple[str, dict]]: """[(mail kind, values)] for one folder's alerts: one mail for failures, one for overdue chains.""" out = [] - for kind, mail_kind in (('failed', 'verify_failed'), ('overdue', 'verify_overdue')): + for kind, mail_kind in (('failed', 'verify_failed'), ('overdue', 'verify_overdue'), + ('test_failed', 'test_failed'), ('test_overdue', 'test_overdue')): mine = [a for a in rows if a['kind'] == kind] if not mine: continue diff --git a/docker-compose.yaml b/docker-compose.yaml index 11db7f4..7503fcf 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -306,6 +306,8 @@ services: - BACKUP_API_PORT=8082 # the dashboard exports the stack's proxy image for proxy VMs (deploy and update); same token as BACKUP_API_TOKEN - DASHBOARD_URL=http://dashboard:5000 + # test restores ask the console service whether a restored VM booted (its token is derived from HCM_SECRET_KEY) + - CONSOLE_API_URL=http://console:8084 # self-proxy inside this stack (optional; remote proxies are registered in the dashboard) - PROXY_API_URL=${PROXY_API_URL:-http://proxy:8083} - PROXY_API_TOKEN=${PROXY_API_TOKEN:-} diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6b29c0a..3094303 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,30 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Added +- **Test restores.** A test plan per folder (Backup → Schedules → **Test restores**) restores the newest backup of + its VMs as temporary VMs, starts them, checks that they come up and deletes them again. A round every N days: + fixed VMs plus N picked at random from the folder's backed-up VMs (longest untested first, a tested VM rests N + weeks). Tests run on the folder's DR cluster at any hour (paused during the folder's backups), else on the VM's + own cluster inside the plan's hours, outside backups, and only when they fit before the next backups; one test + per target cluster at a time, and only when a node has room for the VM under the balancer's RAM ceiling. + - **Boot test**: NICs disconnected; a pass is the guest agent answering or, without an agent, a login / lock / + sign-in screen on the console (the console service's classifier, now also recognising stop screens, BitLocker + recovery, "no bootable device", GRUB rescue and emergency mode as failures). The last screenshot is kept. + VMs without a guest agent are marked *agentless: screen check only*. + - **Network test**: NICs on an isolated test VLAN (refused when another VM on the target cluster uses it), then + ping and TCP port checks from a proxy NIC on that VLAN (proxy job `netcheck`, bound to that NIC so a restored + VM's production IP never reaches the production VM). HCM never touches the test VLAN. + - Options, off by default: keep a failed test VM for N hours; a byte budget per round. + - Results under Runs → **Test restores** (verdict, target, point age, restore and boot time, checks, + screenshot) and a **Tested** column on the restore points. A failed test and a fixed VM without a passed test + for twice the interval raise a badge on the cluster card and a mail to the closest administrator. +- **Proxy deploy: Test VLAN** adds a second NIC for the network checks. Proxy **0.6.0**: job `netcheck`, + `iproute2` and `iputils-ping` in the image; proxies deployed from now on run with host networking (older ones + show *network tests: redeploy*). + ## [1.6.0] ### Added diff --git a/docs/administration.md b/docs/administration.md index 5d8980b..60b2894 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -395,7 +395,10 @@ from its MAC addresses; the status column says **VM detected** when that worked. connection** repeats the probe. A paused proxy is not used for new runs. **Deploy a proxy VM** (same panel) creates the proxy VM for you: pick the cluster, a name, VLAN, -sizes and DHCP or a static address, and the backup service uploads an Ubuntu cloud image to the +sizes, DHCP or a static address, and optionally a **Test VLAN** (a second NIC on an isolated VLAN, for the +network checks of test restores; left unconfigured, the proxy brings it up only during a check). Proxies +deployed from 1.7.0 on run their container with host networking so they can use that NIC; an older proxy +shows *network tests: redeploy* in the proxies table. The backup service uploads an Ubuntu cloud image to the cluster once, creates the VM with a cloud-init document that installs Docker and the proxy container, waits for its address and registers it with a freshly generated token. The list below the form follows the deployment; a finished one shows up in the proxies table with its VM diff --git a/docs/manual/05-backup.md b/docs/manual/05-backup.md index ee4c01f..152be12 100644 --- a/docs/manual/05-backup.md +++ b/docs/manual/05-backup.md @@ -128,6 +128,45 @@ while it is read, must not raise an alarm). A point that still fails is marked * own administrators, else the customer's, else the MSP's, else the installation's. A chain with a point not verified for twice the interval gets an amber badge and a mail of its own. Mail needs Settings → Mail. +### Test restores + +Verification proves the backup's bytes are what was written; a **test restore** proves the VM boots from them. +It restores the VM's newest point as a temporary VM (`-hcmtest-`, tagged `hcm-testrestore`, new MAC +addresses), starts it, waits for a sign of life, keeps a screenshot of its console, and deletes it again. + +A **test plan** (Backup → Schedules → **Test restores**) belongs to the folder: + +- **A round every** N days: the plan's fixed VMs (**always test**) plus **Random VMs per round** picked from the + folder's backed-up VMs, longest untested first. A tested VM rests a number of weeks before it can be picked + again; **never test** keeps a VM out of the random pick. +- **Where**: on the folder's **DR cluster** when it has one with a proxy, at any hour (paused while the folder's + backups run). Without a DR cluster, on each VM's own cluster, only within **Hours on a production cluster**, + outside backups, and only when the test is expected to finish before the next backups start. One test per + target cluster at a time; a test needs a node with room for the VM's memory under the balancer's RAM ceiling, + otherwise it is skipped with that reason. +- **Boot test (no network)**: the NICs stay disconnected. A pass is the **guest agent** answering (works without + network) or, without an agent, the **console screen** showing a login, lock or sign-in screen. A stop screen, + a BitLocker recovery screen (the vTPM did not unseal), "no bootable device", a crash, or nothing within + **Sign of life within** minutes is a fail. A VM without a guest agent in production is marked *agentless: + screen check only*, so a weaker pass is never mistaken for an agent pass. +- **Network test (test VLAN)**: the NICs go onto an isolated **test VLAN**, and after the boot check a proxy + pings the VM and tries its ports (per VM, or the plan's default; without ports only ping counts, and Windows + answers no ping by default). The checks run from a **proxy NIC on the test VLAN**, with the plan's **probe + address** (a free address in the VMs' subnet, with prefix): HCM itself never touches the test VLAN. Restored + VMs keep their addresses and names, so HCM refuses a VLAN that any other VM on the target cluster uses; whether + the VLAN is routed elsewhere it cannot see, so keep it isolated on the switches too. The proxy needs to be + deployed with 1.7.0 or later (it runs with host networking) and with a **Test VLAN** NIC (Settings → Backup → + Deploy a proxy VM); the plan card warns when no proxy can run the checks. +- Options, off by default: **Keep a failed test VM for inspection** (hours), and a **Byte budget per round** (a + test writes the whole VM: tests that would pass the budget are skipped in that round). + +**Run now** queues a round at once (it still waits for a moment the target may take it). Results appear under +**Runs → Test restores** (how it passed or failed, the target, the age of the point used, restore and boot time, +network checks, the screenshot) and as a **Tested** column on the restore points. A failed test is a red badge on +the cluster card and a mail to the closest administrator; a fixed VM without a passed test for twice the plan's +interval gets an amber badge and a mail. Test VMs are deleted after each test; a sweep every 15 minutes removes any +left behind (it only ever deletes VMs that carry both the tag and the name mark). + ## Plans ![Plans](img/backup-schedules.png) @@ -221,7 +260,7 @@ runs on the cluster and is followed under Runs. ![Runs](img/backup-runs.png) -The history of runs, restores, imports and verifications for the cluster with their state and detail: +The history of runs, test restores, restores, imports and verifications for the cluster with their state and detail: what kind of point a run produced, how much it copied, why a run was skipped or deferred, which proxy verified a point, how much it read and how long it took. A run is **deferred** when the cluster is updating itself or a node is missing; HyperCore cannot snapshot diff --git a/postgres/init/053_test_restores.sql b/postgres/init/053_test_restores.sql new file mode 100644 index 0000000..39778a5 --- /dev/null +++ b/postgres/init/053_test_restores.sql @@ -0,0 +1,89 @@ +-- ============================================================================= +-- 053_test_restores.sql +-- Test restores (plans/PLAN-test-restores.md, T1 + T2, 2026-11-21). +-- +-- A test plan belongs to a folder: which VMs (fixed, and/or N at random from the folder's backed-up VMs), +-- how often, which level (boot: NICs disconnected; network: NICs on an isolated test VLAN plus ping and port +-- checks run from the proxy's test NIC). Each test restores the newest point as a new VM on the folder's DR +-- cluster (else the VM's own cluster), waits for a sign of life (guest agent, else the console screen), +-- records the verdict with a screenshot, and deletes the VM. Idempotent. +-- ============================================================================= + +CREATE TABLE IF NOT EXISTS backup.test_plans ( + id SERIAL PRIMARY KEY, + folder_id UUID REFERENCES config.folders (folder_id) ON DELETE CASCADE, -- NULL: unfiled clusters + name TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + interval_days INTEGER NOT NULL DEFAULT 7 CHECK (interval_days BETWEEN 1 AND 90), + hours_from TEXT NOT NULL DEFAULT '01:00', -- for a test on a production cluster + hours_until TEXT NOT NULL DEFAULT '06:00', + random_count INTEGER NOT NULL DEFAULT 0 CHECK (random_count BETWEEN 0 AND 50), + rest_weeks INTEGER NOT NULL DEFAULT 4 CHECK (rest_weeks BETWEEN 1 AND 52), + level TEXT NOT NULL DEFAULT 'boot' CHECK (level IN ('boot', 'network')), + test_vlan INTEGER CHECK (test_vlan BETWEEN 0 AND 4094), + probe_address TEXT, -- the proxy's address on the test VLAN, e.g. 172.16.0.250/25 + default_ports INTEGER[] NOT NULL DEFAULT '{}', + timeout_minutes INTEGER NOT NULL DEFAULT 10 CHECK (timeout_minutes BETWEEN 2 AND 120), + keep_failed_hours INTEGER CHECK (keep_failed_hours BETWEEN 1 AND 168), -- NULL: off (delete at once) + byte_budget_gb INTEGER CHECK (byte_budget_gb > 0), -- NULL: off (no limit) + last_run_at TIMESTAMPTZ, -- when the last round was queued + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_by TEXT +); +CREATE INDEX IF NOT EXISTS ix_test_plans_folder ON backup.test_plans (folder_id); + +-- fixed members and exclusions of a plan (the random pool is every backed-up VM of the folder minus these) +CREATE TABLE IF NOT EXISTS backup.test_plan_vms ( + plan_id INTEGER NOT NULL REFERENCES backup.test_plans (id) ON DELETE CASCADE, + cluster_id UUID NOT NULL, + vm_uuid TEXT NOT NULL, + vm_name TEXT, + mode TEXT NOT NULL CHECK (mode IN ('fixed', 'exclude')), + ports INTEGER[], -- network level: this VM's ports (NULL: the plan's) + PRIMARY KEY (plan_id, cluster_id, vm_uuid) +); + +-- one row per VM test +CREATE TABLE IF NOT EXISTS backup.test_runs ( + id BIGSERIAL PRIMARY KEY, + plan_id INTEGER REFERENCES backup.test_plans (id) ON DELETE SET NULL, + folder_id UUID, + round_at TIMESTAMPTZ, -- the round (plan's last_run_at) it belongs to + cluster_id UUID NOT NULL, -- the VM's own cluster + vm_uuid TEXT NOT NULL, + vm_name TEXT, + picked TEXT, -- fixed | random + level TEXT NOT NULL DEFAULT 'boot', + status TEXT NOT NULL DEFAULT 'queued', -- queued | running | passed | failed | skipped | error + verdict TEXT, -- agent | screen | ... (how it passed or failed) + agent TEXT, -- the source VM's guest agent: available | unavailable | unknown + point_id BIGINT, + point_created_at TIMESTAMPTZ, + target_cluster_id UUID, + proxy_id BIGINT, + restore_id BIGINT, + restored_vm_uuid TEXT, + bytes BIGINT, + checks JSONB, -- network level: [{ip, ping, ports: {port: ok}}] + screenshot BYTEA, + detail TEXT, + queued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + started_at TIMESTAMPTZ, + restored_at TIMESTAMPTZ, + booted_at TIMESTAMPTZ, + finished_at TIMESTAMPTZ, + keep_until TIMESTAMPTZ, -- a failed VM kept for inspection until then + cleaned_at TIMESTAMPTZ -- the test VM was deleted +); +CREATE INDEX IF NOT EXISTS ix_test_runs_vm ON backup.test_runs (cluster_id, vm_uuid, id DESC); +CREATE INDEX IF NOT EXISTS ix_test_runs_status ON backup.test_runs (status) WHERE status IN ('queued', 'running'); +CREATE INDEX IF NOT EXISTS ix_test_runs_folder ON backup.test_runs (folder_id, id DESC); + +-- alerts: test kinds next to the verification ones, per VM +ALTER TABLE backup.verify_alerts ADD COLUMN IF NOT EXISTS vm_uuid TEXT; +ALTER TABLE backup.verify_alerts DROP CONSTRAINT IF EXISTS verify_alerts_kind_check; +ALTER TABLE backup.verify_alerts ADD CONSTRAINT verify_alerts_kind_check + CHECK (kind IN ('failed', 'overdue', 'test_failed', 'test_overdue')); +CREATE UNIQUE INDEX IF NOT EXISTS ux_verify_alerts_open_test + ON backup.verify_alerts (cluster_id, vm_uuid, kind) WHERE resolved_at IS NULL AND kind IN ('test_failed', 'test_overdue'); diff --git a/proxy/Dockerfile b/proxy/Dockerfile index 1e58008..abc5774 100644 --- a/proxy/Dockerfile +++ b/proxy/Dockerfile @@ -3,9 +3,9 @@ FROM python:3.12-slim-bookworm # qemu-utils: qemu-img / qemu-nbd; cifs-utils + nfs-common: mounting backup targets; # util-linux: blockdev/sfdisk/losetup; udev: udevadm settle; lvm2 + dmsetup: file-level recovery # (COW overlays, LVM import); ntfs-3g: NTFS fallback; genisoimage: ISO delivery; procps: ps/free for -# the support bundle; tini: PID 1 (see below) +# the support bundle; tini: PID 1 (see below); iproute2 + iputils-ping: network checks of test restores RUN apt-get update \ - && apt-get install -y --no-install-recommends qemu-utils cifs-utils nfs-common util-linux fdisk udev lvm2 dmsetup cryptsetup-bin ntfs-3g genisoimage openssl procps tini \ + && apt-get install -y --no-install-recommends qemu-utils cifs-utils nfs-common util-linux fdisk udev lvm2 dmsetup cryptsetup-bin ntfs-3g genisoimage openssl procps tini iproute2 iputils-ping \ && rm -rf /var/lib/apt/lists/* WORKDIR /app diff --git a/proxy/api.py b/proxy/api.py index bc1daff..ee52587 100644 --- a/proxy/api.py +++ b/proxy/api.py @@ -3,7 +3,7 @@ GET /health liveness GET /identity hostname, MAC addresses, capabilities (token required) - POST /jobs/ kind in backup | flatten | synthesize | verify | sweep | prune | delete_chain | stage | bench -> {id} + POST /jobs/ kind in backup | flatten | synthesize | verify | sweep | prune | delete_chain | stage | bench | netcheck -> {id} GET /jobs recent jobs GET /jobs/ state, progress, result or error DELETE /jobs/ request cancellation @@ -45,6 +45,7 @@ 'delete_chain': ('target', 'chain_dir'), 'stage': ('target', 'chain_dir', 'seq', 'devices'), 'bench': ('target',), + 'netcheck': ('mac', 'probe', 'targets'), } diff --git a/proxy/identity.py b/proxy/identity.py index 99f0220..88eba08 100644 --- a/proxy/identity.py +++ b/proxy/identity.py @@ -9,10 +9,18 @@ import socket import subprocess -VERSION = '0.5.7' +VERSION = '0.6.0' _SKIP_PREFIXES = ('lo', 'docker', 'veth', 'br-', 'virbr', 'cni', 'flannel', 'tun', 'tap', 'wg') +def _host_network() -> bool: + try: + import netcheck + return netcheck.host_network() + except Exception: # noqa: BLE001 + return False + + def host_macs(host_net_dir: str) -> list[dict]: """[{ifname, mac}] for physical-looking interfaces found under a bind-mounted /sys/class/net.""" out = [] @@ -57,7 +65,9 @@ def identity(cfg, backend_name: str, nbd_free: int | None) -> dict: 'qemu_img': _tool_version(['qemu-img', '--version']), 'mount_cifs': shutil.which('mount.cifs') is not None, 'mount_nfs': shutil.which('mount.nfs') is not None or shutil.which('mount.nfs4') is not None, - 'jobs': ['backup', 'flatten', 'synthesize', 'verify', 'sweep', 'prune', 'delete_chain', 'stage', 'bench'], + 'jobs': ['backup', 'flatten', 'synthesize', 'verify', 'sweep', 'prune', 'delete_chain', 'stage', 'bench', 'netcheck'], + # network tests of test restores need the VM's own NICs: true when the container runs with --network host + 'host_network': _host_network(), # a resized disk arrives with `full: true` and is written without a backing file 'full_flag': True, # verify accepts upto_seq and reports progress (points, bytes) diff --git a/proxy/jobs.py b/proxy/jobs.py index 446860a..923e192 100644 --- a/proxy/jobs.py +++ b/proxy/jobs.py @@ -5,6 +5,7 @@ flatten materialise one point as flat qcow2 files + the supplied definition (restore directory) synthesize a point, read through its chain, as the base of a new chain (a synthetic full) verify re-hash the points of a chain (one, all, or everything up to a seq) against their manifests +netcheck ping / TCP checks of a test-restored VM on the test VLAN, through the proxy's test NIC sweep remove stale restore directories under a folder on the target bench measure write/read throughput onto a target through the paths a backup and a restore use @@ -78,7 +79,7 @@ def __init__(self, cfg, backend, mounter): # ---------------------------------------------------------------- registry def submit(self, kind: str, request: dict) -> Job: runner = {'backup': self.run_backup, 'flatten': self.run_flatten, 'synthesize': self.run_synthesize, 'verify': self.run_verify, 'sweep': self.run_sweep, - 'prune': self.run_prune, 'delete_chain': self.run_delete_chain, 'stage': self.run_stage, 'bench': self.run_bench}[kind] + 'prune': self.run_prune, 'delete_chain': self.run_delete_chain, 'stage': self.run_stage, 'bench': self.run_bench, 'netcheck': self.run_netcheck}[kind] job = Job(kind, request) with self._lock: self.jobs[job.id] = job @@ -305,6 +306,18 @@ def prog(n, _b=done): finally: self._release_target(req) + # ---------------------------------------------------------------- netcheck + def run_netcheck(self, job: Job) -> dict: + """request: {mac: the test NIC's MAC, probe: '172.16.0.250/25', targets: [{ip, ports: [int]}]}. + Ping and TCP checks of a test-restored VM on the test VLAN, through the test NIC only (netcheck.py).""" + import netcheck + req = job.request + job.progress = {'targets': len(req.get('targets') or [])} + try: + return netcheck.run(req['mac'], req['probe'], req.get('targets') or []) + except netcheck.NetcheckError as e: + raise RuntimeError(str(e)) from None + # ---------------------------------------------------------------- sweep def run_sweep(self, job: Job) -> dict: """request: {target, folder, older_than_hours (default 24)} — removes /_restore/* older than the limit.""" diff --git a/proxy/netcheck.py b/proxy/netcheck.py new file mode 100644 index 0000000..40b95d9 --- /dev/null +++ b/proxy/netcheck.py @@ -0,0 +1,138 @@ +""" +netcheck.py — network checks of a test-restored VM on an isolated test VLAN (plans/PLAN-test-restores.md, T2). + +The proxy VM has a second NIC on the test VLAN (added at deploy, or later with a power cycle). For one check +run the NIC is brought up with a temporary probe address, every target is pinged and its TCP ports tried, and +the address is removed and the NIC taken down again. HyperCore Manager never touches the test VLAN itself. + +A restored VM keeps its production IP address, and the proxy's management NIC may well sit in the same subnet. +A plain connect would then leave through the management NIC and could reach the *production* VM: a false pass. +So every probe is bound to the test NIC (SO_BINDTODEVICE for TCP, `ping -I` for ICMP), the probe address is +added as a /32 (no subnet route that could compete with the management NIC's), and each target gets a host +route through the test NIC for the duration of the check. The caller refuses targets that are the proxy's own +infrastructure (its gateway, the share, HyperCore Manager), so those routes never cut the proxy off. + +Needs the proxy container to run in the host's network namespace (`--network host`, proxies deployed from +1.7.0 on) and to be privileged (it is): only then does it see and configure the VM's NICs. +""" +from __future__ import annotations + +import ipaddress +import os +import socket +import subprocess +import time + +SYS_NET = '/sys/class/net' + + +class NetcheckError(Exception): + pass + + +def interface_for_mac(mac: str, sys_net: str = SYS_NET) -> str | None: + """The interface in this network namespace carrying `mac`, or None.""" + want = (mac or '').strip().lower() + try: + names = os.listdir(sys_net) + except OSError: + return None + for n in sorted(names): + try: + with open(os.path.join(sys_net, n, 'address')) as fh: + if fh.read().strip().lower() == want: + return n + except OSError: + continue + return None + + +def host_network(sys_net: str = SYS_NET, host_sys_net: str | None = None) -> bool: + """True when this container sees the VM's own NICs, i.e. it runs with --network host: one of the host's + physical interfaces (from the bind-mounted host /sys) is present in our own namespace.""" + host_sys_net = host_sys_net or os.environ.get('PROXY_HOST_NET') or '' + if not host_sys_net: + return False + try: + host = {n for n in os.listdir(host_sys_net) if not n.startswith(('lo', 'docker', 'veth', 'br-'))} + mine = set(os.listdir(sys_net)) + except OSError: + return False + return bool(host & mine) + + +def parse_probe(probe: str) -> ipaddress.IPv4Interface: + try: + iface = ipaddress.IPv4Interface(str(probe).strip()) + except ValueError: + raise NetcheckError(f'the probe address {probe!r} is not an IPv4 address with a prefix (e.g. 172.16.0.250/25)') from None + if iface.network.prefixlen == 32: + raise NetcheckError('the probe address needs the test subnet\'s prefix (e.g. /24), not /32') + return iface + + +def _ip(*args: str) -> None: + r = subprocess.run(['ip', *args], capture_output=True, text=True, timeout=15) + if r.returncode != 0: + raise NetcheckError(f"ip {' '.join(args)}: {r.stderr.strip() or r.returncode}") + + +def ping(ip: str, dev: str, count: int = 2, wait_s: int = 2) -> bool: + r = subprocess.run(['ping', '-n', '-q', '-I', dev, '-c', str(count), '-W', str(wait_s), ip], + capture_output=True, text=True, timeout=count * wait_s + 10) + return r.returncode == 0 + + +def tcp(ip: str, port: int, dev: str, timeout: float = 3.0) -> bool: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, dev.encode() + b'\0') + s.settimeout(timeout) + s.connect((ip, int(port))) + return True + except OSError: + return False + finally: + s.close() + + +def run(mac: str, probe: str, targets: list[dict], settle_s: float = 3.0, ping_fn=ping, tcp_fn=tcp, ip_fn=_ip, + sys_net: str = SYS_NET) -> dict: + """targets: [{ip, ports: [int]}]. Returns {'interface', 'results': {ip: {'ping': bool, 'ports': {port: bool}}}}.""" + dev = interface_for_mac(mac, sys_net) + if not dev: + raise NetcheckError(f'no interface with MAC {mac} in the proxy: it needs a NIC on the test VLAN and must run ' + 'with host networking (proxies deployed from 1.7.0 on; redeploy an older one)') + pr = parse_probe(probe) + cleaned: list[ipaddress.IPv4Address] = [] + for t in targets: + try: + cleaned.append(ipaddress.IPv4Address(str(t['ip']))) + except (KeyError, ValueError): + raise NetcheckError(f"not an IPv4 address: {t.get('ip')!r}") from None + ip_fn('link', 'set', dev, 'up') + ip_fn('addr', 'add', f'{pr.ip}/32', 'dev', dev) + routes = [] + try: + for a in cleaned: + # a host route per target through the test NIC, for the few seconds of the check: the management + # NIC's subnet route stays, but this address is reached on the test VLAN only + ip_fn('route', 'replace', f'{a}/32', 'dev', dev, 'src', str(pr.ip)) + routes.append(a) + time.sleep(settle_s) # link up, switch learns the port + results = {} + for t in targets: + ip = str(t['ip']) + results[ip] = {'ping': ping_fn(ip, dev), 'ports': {int(p): tcp_fn(ip, int(p), dev) for p in t.get('ports') or []}} + return {'interface': dev, 'probe': str(pr.ip), 'results': results} + finally: + for a in routes: + try: + ip_fn('route', 'del', f'{a}/32', 'dev', dev) + except NetcheckError: + pass + for args in (('addr', 'del', f'{pr.ip}/32', 'dev', dev), ('link', 'set', dev, 'down')): + try: + ip_fn(*args) + except NetcheckError: + pass diff --git a/tests/test_backup_deploy.py b/tests/test_backup_deploy.py index 250bba9..b6eb360 100644 --- a/tests/test_backup_deploy.py +++ b/tests/test_backup_deploy.py @@ -169,3 +169,11 @@ def test_push_image_leaves_a_running_proxy_alone_and_times_out(monkeypatch): monkeypatch.setattr(dp.time, 'monotonic', lambda: next(clock)) with pytest.raises(dp.IncrementalError, match='bootstrap receiver'): dp.push_image('10.0.0.9', 'tok', timeout=1000, sleep=lambda s: None, fingerprint_of=fp) + + +def test_a_proxy_can_get_a_test_vlan_nic_and_runs_with_host_networking(): + """Network checks of test restores need the proxy to see its own NICs (--network host) and a NIC on the test VLAN.""" + body = dp.vm_body('px', 2, 4, 7, 'ud', 'md', test_vlan=999) + assert [n['vlan'] for n in body['dom']['netDevs']] == [7, 999] and all(n['connected'] for n in body['dom']['netDevs']) + assert len(dp.vm_body('px', 2, 4, 7, 'ud', 'md')['dom']['netDevs']) == 1 + assert '--network host' in dp.RUN_SH and '-p 8083:8083' not in dp.RUN_SH diff --git a/tests/test_backup_testrestore.py b/tests/test_backup_testrestore.py new file mode 100644 index 0000000..7049532 --- /dev/null +++ b/tests/test_backup_testrestore.py @@ -0,0 +1,294 @@ +"""backup/testrestore.py: test restores (plans/PLAN-test-restores.md, T1 + T2) with fakes for the database, the +clusters, the restore path, the console service and the proxy.""" +import importlib +import os +import sys +import threading +import types +from datetime import datetime, timedelta, timezone + +import pytest + +_BACKUP = os.path.join(os.path.dirname(__file__), '..', 'backup') +_CLASH = ('config', 'db', 'log', 'api', 'hypercore', 'jobs', 'scheduler', 'incremental', 'proxy_client', 'manifest_names', + 'recurrence', 'verifier', 'policies', 'planner', 'predict', 'testrestore', 'restore', 'vm_definition') + + +def _import(): + saved = {n: sys.modules.pop(n) for n in _CLASH if n in sys.modules} + sys.path.insert(0, _BACKUP) + try: + tr = importlib.import_module('testrestore') + hcm = importlib.import_module('hypercore') + finally: + sys.path.remove(_BACKUP) + for n in _CLASH: + sys.modules.pop(n, None) + sys.modules.update(saved) + return tr, hcm + + +tr, hcm = _import() +UTC = timezone.utc +NOW = datetime(2026, 11, 22, 2, 0, tzinfo=UTC) + + +# ------------------------------------------------------------------ pure rules +def test_memory_fits_respects_the_ceiling_and_skips_witness_nodes(): + nodes = [{'memSize': 64 << 30, 'totalMemUsageBytes': 50 << 30, 'allowRunningVMs': True}, + {'memSize': 64 << 30, 'totalMemUsageBytes': 1 << 30, 'allowRunningVMs': False}] + assert not tr.memory_fits(nodes, 8 << 30, 85) # 58/64 = 91 % > 85 %; the empty node is a witness + assert tr.memory_fits(nodes, 4 << 30, 85) # 54/64 = 84 % + assert tr.max_free_memory(nodes) == 14 << 30 + + +def test_judge_checks_ports_decide_and_ping_only_without_ports(): + assert tr.judge_checks([{'ip': '10.0.0.5', 'ping': False, 'ports': {3389: True, 443: True}}])[0] + ok, why = tr.judge_checks([{'ip': '10.0.0.5', 'ping': True, 'ports': {3389: True, 1433: False}}]) + assert not ok and 'port(s) 1433 closed' in why + assert tr.judge_checks([{'ip': '10.0.0.5', 'ping': True, 'ports': {}}])[0] + assert not tr.judge_checks([{'ip': '10.0.0.5', 'ping': False, 'ports': {}}])[0] + assert tr.judge_checks([{'ip': '10.0.0.5', 'ping': False, 'ports': {443: False}}, + {'ip': '10.0.1.5', 'ping': False, 'ports': {443: True}}])[0], 'one address answering is enough' + + +class FakeDB: + def __init__(self): + self.members = [] + self.backed_up = [] + self.runs = {} + self.alerts = [] + self.resolved = [] + self.restores = {} + self.clusters = [{'cluster_id': 'prod', 'cluster_name': 'Prod', 'role': 'production', 'timezone': 'UTC'}] + self.proxies = {'prod': [{'id': 1, 'name': 'px', 'vm_uuid': 'pxvm', 'cluster_id': 'prod', 'capabilities': {}}]} + + def test_plan_vms(self, pid): return self.members + def backed_up_vms(self, f): return self.backed_up + def folder_clusters(self, f): return self.clusters + def get_proxies(self, cid, enabled_only=False): return self.proxies.get(cid, []) + def get_proxy(self, pid, with_secret=False): return next(p for ps in self.proxies.values() for p in ps if p['id'] == pid) + def cluster_role(self, cid): return next((c['role'] for c in self.clusters if c['cluster_id'] == cid), 'production') + def update_test_run(self, rid, **f): self.runs.setdefault(rid, {}).update(f) + def ram_limit_percent(self, cid): return 85.0 + def get_chain(self, cid): return {'id': cid, 'cluster_id': 'prod', 'target_id': 9, 'vm_name': 'dc01', 'folder_slug': 'F', 'chain_dir': 'F/dc01.chain'} + def get_share(self, sid, with_secret=False): return {'uri_base': 'smb://10.0.0.20/backups'} + def add_restore(self, point, chain, name, params, requested_by=None, cluster_id=None): + rid = len(self.restores) + 1 + self.restores[rid] = {'id': rid, 'target_name': name, 'params': params, 'cluster_id': cluster_id, 'requested_by': requested_by} + return rid + def get_restore(self, rid): return self.restores.get(rid) + def raise_test_alert(self, kind, folder, cid, vm, name, detail): self.alerts.append((kind, vm, detail)); return True + def resolve_test_alerts(self, cid, vm, kind=None): self.resolved.append(vm); return 1 + + +class FakeHC: + def __init__(self, vms=None, nodes=None, boot=None): + self.vms = {v['uuid']: v for v in (vms or [])} + self.nodes = nodes or [{'memSize': 64 << 30, 'totalMemUsageBytes': 8 << 30, 'allowRunningVMs': True}] + self.boot = list(boot or []) # successive states of the restored VM + self.actions = [] + + def list_vms_full(self): return list(self.vms.values()) + def list_nodes(self): return self.nodes + def get_vm(self, u): + if u == 'restored' and self.boot: + v = self.boot.pop(0) if len(self.boot) > 1 else self.boot[0] + return dict(v, uuid='restored', name='dc01-hcmtest-1', tags='windows,hcm-testrestore') + if u not in self.vms: + raise hcm.HyperCoreError('not found') + return self.vms[u] + def vm_action(self, u, a): self.actions.append((a, u)); return '' + def delete_vm(self, u): self.actions.append(('DELETE', u)); self.vms.pop(u, None); return '' + + +@pytest.fixture +def world(monkeypatch): + db = FakeDB() + src = FakeHC(vms=[{'uuid': 'vm1', 'name': 'dc01', 'state': 'RUNNING', 'guestAgentState': 'AVAILABLE', + 'netDevs': [{'vlan': 10, 'ipv4Addresses': ['10.0.0.5']}]}]) + tgt = FakeHC(boot=[{'state': 'RUNNING', 'guestAgentState': 'UNAVAILABLE'}, {'state': 'RUNNING', 'guestAgentState': 'AVAILABLE'}]) + clients = {'prod': src, 'dr': tgt} + monkeypatch.setattr(tr, 'db', db) + monkeypatch.setattr(tr, 'jobs', types.SimpleNamespace(client_for=lambda c: clients[c], preflight=lambda hc: {'ok': True})) + monkeypatch.setattr(tr.incremental, 'wait_task', lambda *a, **k: None) + restore_mod = types.SimpleNamespace(run_restore=lambda rid: db.restores[rid].update( + status='COMPLETE', created_uuid='restored', message="restored as 'dc01-hcmtest-1' (1 disk(s), 2048 MiB written)")) + monkeypatch.setitem(sys.modules, 'restore', restore_mod) + monkeypatch.setattr(tr, 'console_bootcheck', lambda cid, vm: {'verdict': 'wait', 'detail': 'boot logo', 'png': None}) + tr._running.clear() + return types.SimpleNamespace(db=db, src=src, tgt=tgt, clients=clients) + + +PLAN = {'id': 3, 'name': 'Weekly', 'folder_id': 'F1', 'level': 'boot', 'timeout_minutes': 10, 'keep_failed_hours': None, + 'test_vlan': None, 'probe_address': None, 'default_ports': [], 'random_count': 0, 'rest_weeks': 4} +RUN = {'id': 1, 'cluster_id': 'prod', 'vm_uuid': 'vm1', 'vm_name': 'dc01'} +POINT = {'id': 50, 'chain_id': 7, 'created_at': NOW - timedelta(hours=5), 'restore_bytes': 2 << 30, + 'definition': {'mem': 4 << 30, 'netDevs': [{'ipv4Addresses': ['10.0.0.5']}]}} + + +class Clock: + def __init__(self): self.t = 0.0 + def __call__(self): return self.t + def sleep(self, s): self.t += s + + +# ------------------------------------------------------------------ rounds +def test_a_round_takes_the_fixed_vms_and_the_longest_untested_from_the_pool(world): + db = world.db + db.members = [{'cluster_id': 'prod', 'vm_uuid': 'dc', 'vm_name': 'dc01', 'mode': 'fixed', 'ports': None}, + {'cluster_id': 'prod', 'vm_uuid': 'noisy', 'vm_name': 'build', 'mode': 'exclude', 'ports': None}] + db.backed_up = [{'cluster_id': 'prod', 'vm_uuid': 'dc', 'vm_name': 'dc01', 'last_tested': None}, + {'cluster_id': 'prod', 'vm_uuid': 'noisy', 'vm_name': 'build', 'last_tested': None}, + {'cluster_id': 'prod', 'vm_uuid': 'a', 'vm_name': 'app', 'last_tested': NOW - timedelta(days=60)}, + {'cluster_id': 'prod', 'vm_uuid': 'b', 'vm_name': 'sql', 'last_tested': None}, + {'cluster_id': 'prod', 'vm_uuid': 'c', 'vm_name': 'web', 'last_tested': NOW - timedelta(days=3)}] + picked = tr.select_vms(dict(PLAN, random_count=2), NOW) + assert [(v['vm_name'], v['picked']) for v in picked] == [('dc01', 'fixed'), ('sql', 'random'), ('app', 'random')] + # web was tested 3 days ago: it rests 4 weeks; build is excluded; dc01 is fixed, never also random + + +def test_the_target_is_the_dr_cluster_when_the_folder_has_one_with_a_proxy(world): + db = world.db + assert tr.target_for('F1', 'prod') == ('prod', 'production') + db.clusters.append({'cluster_id': 'dr', 'cluster_name': 'DR', 'role': 'dr', 'timezone': 'UTC'}) + assert tr.target_for('F1', 'prod') == ('prod', 'production'), 'a DR cluster without a proxy cannot restore' + db.proxies['dr'] = [{'id': 2, 'name': 'px-dr', 'vm_uuid': 'p2', 'cluster_id': 'dr'}] + assert tr.target_for('F1', 'prod') == ('dr', 'dr') + + +# ------------------------------------------------------------------ one test +def test_a_boot_test_restores_disconnected_passes_on_the_agent_and_deletes_the_vm(world): + c = Clock() + assert tr.run_test(RUN, PLAN, 'dr', POINT, sleep=c.sleep, clock=c) == 'passed' + r = world.db.restores[1] + assert r['cluster_id'] == 'dr' and r['target_name'] == 'dc01-hcmtest-1' and r['requested_by'] == 'test restore' + assert r['params']['nic_connected'] is False and r['params']['mac_policy'] == 'new' and r['params']['start'] is True + assert 'hcm-testrestore' in r['params']['extra_tags'] and 'vlan' not in r['params'] + run = world.db.runs[1] + assert run['status'] == 'passed' and run['verdict'] == 'agent' and run['agent'] == 'available' and run['bytes'] == 2048 << 20 + assert ('STOP', 'restored') in world.tgt.actions and ('DELETE', 'restored') in world.tgt.actions and run['cleaned_at'] + assert world.db.resolved == ['vm1'] and world.db.alerts == [] + + +def test_without_an_agent_the_console_screen_decides(world, monkeypatch): + world.tgt.boot = [{'state': 'RUNNING', 'guestAgentState': 'UNAVAILABLE'}] + screens = iter([{'verdict': 'wait', 'detail': 'boot logo', 'png': None}, + {'verdict': 'pass', 'detail': 'lock screen', 'png': 'iVBORw0K'}]) + monkeypatch.setattr(tr, 'console_bootcheck', lambda cid, vm: next(screens)) + c = Clock() + assert tr.run_test(RUN, PLAN, 'dr', POINT, sleep=c.sleep, clock=c) == 'passed' + run = world.db.runs[1] + assert run['verdict'] == 'screen' and 'lock screen' in run['detail'] and run['screenshot'] + + +def test_a_stop_screen_or_no_sign_of_life_fails_raises_an_alert_and_can_keep_the_vm(world, monkeypatch): + world.tgt.boot = [{'state': 'RUNNING', 'guestAgentState': 'UNAVAILABLE'}] + monkeypatch.setattr(tr, 'console_bootcheck', lambda cid, vm: {'verdict': 'fail', 'detail': 'BitLocker recovery screen', 'png': 'iVBO'}) + c = Clock() + assert tr.run_test(RUN, dict(PLAN, keep_failed_hours=24), 'dr', POINT, sleep=c.sleep, clock=c) == 'failed' + run = world.db.runs[1] + assert run['verdict'] == 'screen' and 'BitLocker' in run['detail'] and run['keep_until'] + assert ('DELETE', 'restored') not in world.tgt.actions, 'kept for inspection' + assert world.db.alerts and world.db.alerts[0][0] == 'test_failed' + world.db.runs.clear(); world.db.alerts.clear() + monkeypatch.setattr(tr, 'console_bootcheck', lambda cid, vm: {'verdict': 'wait', 'detail': 'boot logo', 'png': None}) + c = Clock() + assert tr.run_test(RUN, PLAN, 'dr', POINT, sleep=c.sleep, clock=c) == 'failed' + assert world.db.runs[1]['verdict'] == 'timeout' and 'within 10 min' in world.db.runs[1]['detail'] + assert ('DELETE', 'restored') in world.tgt.actions, 'not kept: the plan does not ask for it' + + +def test_not_enough_memory_skips_without_restoring(world): + world.tgt.nodes = [{'memSize': 16 << 30, 'totalMemUsageBytes': 13 << 30, 'allowRunningVMs': True}] + assert tr.run_test(RUN, PLAN, 'dr', POINT) == 'skipped' + assert world.db.restores == {} and 'not enough free memory' in world.db.runs[1]['detail'] + + +def test_a_failed_restore_is_a_failed_test_and_its_half_made_vm_is_removed(world, monkeypatch): + db = world.db + sys.modules['restore'].run_restore = lambda rid: db.restores[rid].update(status='ERROR', created_uuid='restored', + message='disk could not be attached') + assert tr.run_test(RUN, PLAN, 'dr', POINT) == 'failed' + assert db.runs[1]['verdict'] == 'restore' and 'could not be attached' in db.runs[1]['detail'] + assert ('DELETE', 'restored') in world.tgt.actions + + +# ------------------------------------------------------------------ network level +NET = dict(PLAN, level='network', test_vlan=999, probe_address='10.0.0.250/24', default_ports=[3389]) + + +def test_the_network_level_refuses_a_vlan_in_use_and_needs_a_capable_proxy(world): + world.tgt.vms = {'prodvm': {'uuid': 'prodvm', 'name': 'erp', 'tags': '', 'netDevs': [{'vlan': 999}]}} + world.db.proxies['dr'] = [{'id': 2, 'name': 'px-dr', 'vm_uuid': 'p2', 'cluster_id': 'dr', 'capabilities': {}}] + assert tr.run_test(RUN, NET, 'dr', POINT) == 'failed' + assert 'in use on the target cluster by erp' in world.db.runs[1]['detail'] and world.db.restores == {} + world.tgt.vms = {} + world.db.runs.clear() + assert tr.run_test(RUN, NET, 'dr', POINT) == 'failed' + assert 'no proxy on the target cluster can test VLAN 999' in world.db.runs[1]['detail'] + + +def test_a_network_test_restores_onto_the_test_vlan_and_checks_ports_through_the_proxy(world, monkeypatch): + world.db.proxies['dr'] = [{'id': 2, 'name': 'px-dr', 'vm_uuid': 'p2', 'cluster_id': 'dr', 'url': 'https://10.0.0.60:8083', + 'capabilities': {'host_network': True, 'jobs': ['netcheck']}}] + world.tgt.vms = {'p2': {'uuid': 'p2', 'name': 'px-dr', 'tags': 'hcm-proxy', + 'netDevs': [{'vlan': 10}, {'vlan': 999, 'macAddress': '7C:4C:58:00:00:99'}]}} + sent = [] + + class PC: + def submit(self, kind, body): sent.append((kind, body)); return 'j1' + def wait(self, j, timeout=0): + return {'result': {'results': {'10.0.0.5': {'ping': False, 'ports': {3389: True}}}}} + monkeypatch.setattr(tr.incremental, 'proxy_client_for', lambda p: PC()) + c = Clock() + assert tr.run_test(RUN, NET, 'dr', POINT, sleep=c.sleep, clock=c) == 'passed' + assert world.db.restores[1]['params']['vlan'] == 999 and world.db.restores[1]['params']['nic_connected'] is True + assert sent == [('netcheck', {'mac': '7C:4C:58:00:00:99', 'probe': '10.0.0.250/24', 'targets': [{'ip': '10.0.0.5', 'ports': [3389]}]})] + assert world.db.runs[1]['checks'] == [{'ip': '10.0.0.5', 'ping': False, 'ports': {3389: True}}] + + +def test_infrastructure_addresses_are_never_probed(world): + proxy = {'url': 'https://10.0.0.60:8083'} + assert tr._infrastructure(proxy, POINT) == {'10.0.0.60', '10.0.0.20'} + + +# ------------------------------------------------------------------ clean-up +def test_cleanup_only_ever_deletes_a_tagged_test_vm(world): + world.tgt.vms = {'x': {'uuid': 'x', 'name': 'erp', 'tags': 'hcm-testrestore', 'state': 'RUNNING'}, + 'y': {'uuid': 'y', 'name': 'erp-hcmtest-5', 'tags': '', 'state': 'RUNNING'}} + assert tr.cleanup('dr', 'x') is False and tr.cleanup('dr', 'y') is False + assert world.tgt.actions == [], 'tag and name mark both required' + + +def test_the_sweep_spares_running_and_kept_tests(world, monkeypatch): + world.tgt.vms = {'a': {'uuid': 'a', 'name': 'dc01-hcmtest-7', 'tags': 'hcm-testrestore', 'state': 'SHUTOFF'}, + 'b': {'uuid': 'b', 'name': 'sql-hcmtest-8', 'tags': 'hcm-testrestore', 'state': 'RUNNING'}, + 'c': {'uuid': 'c', 'name': 'web-hcmtest-9', 'tags': 'hcm-testrestore', 'state': 'RUNNING'}} + db = world.db + db.test_vms_to_clean = lambda now: [] + db.test_vms_in_use = lambda now: {'c'} # kept for inspection + db.running_test_ids = lambda: [8] # still restoring: its uuid is not recorded yet + monkeypatch.setitem(sys.modules, 'cluster_registry', types.SimpleNamespace(list_enabled=lambda: [types.SimpleNamespace(cluster_id='dr')])) + assert tr.sweep(NOW) == 1 + assert [a for a in world.tgt.actions if a[0] == 'DELETE'] == [('DELETE', 'a')] + + +# ------------------------------------------------------------------ the tick +def test_the_tick_runs_one_test_per_target_and_respects_the_byte_budget(world, monkeypatch): + db = world.db + db.clusters.append({'cluster_id': 'dr', 'cluster_name': 'DR', 'role': 'dr', 'timezone': 'UTC'}) + db.proxies['dr'] = [{'id': 2, 'name': 'px-dr', 'vm_uuid': 'p2', 'cluster_id': 'dr'}] + plan = dict(PLAN, enabled=True, interval_days=7, last_run_at=NOW, byte_budget_gb=3, hours_from='01:00', hours_until='06:00') + db.get_test_plans = lambda folder_id=None, all_folders=False: [plan] + db.queued_test_runs = lambda: [dict(RUN, id=1, plan_id=3, round_at=NOW), dict(RUN, id=2, plan_id=3, round_at=NOW, vm_uuid='vm2')] + db.newest_point_for_vm = lambda cid, vm: POINT + db.round_bytes = lambda pid, r: 2 << 30 # 2 GB used + 2 GB > 3 GB budget + monkeypatch.setattr(tr.verifier, 'backup_busy', lambda *a, **k: None) + started = [] + assert tr.tick(NOW, start=lambda run, plan, target, point: started.append((run['id'], target))) == 0 + assert db.runs[1]['status'] == 'skipped' and 'byte budget' in db.runs[1]['detail'] + db.round_bytes = lambda pid, r: 0 + db.runs.clear() + assert tr.tick(NOW, start=lambda run, plan, target, point: started.append((run['id'], target))) == 1 + assert started == [(1, 'dr')], 'the second test waits: one test per target cluster at a time' diff --git a/tests/test_console.py b/tests/test_console.py index 59102f5..e7c62f4 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -264,3 +264,31 @@ def test_carries_input_for_read_only_viewers(): assert rfb.carries_input(bytes([6, 0, 0, 0, 0, 0, 0, 1, 0x61])) # clipboard assert rfb.carries_input(fbur + bytes([4, 1, 0, 0, 0, 0, 0, 0x61])) # batched behind an update request assert not rfb.carries_input(b'RFB 003.008\n') and not rfb.carries_input(b'\x01') + + +# ------------------------------------------------------------------ boot verdict (test restores) +@pytest.mark.parametrize('lines, verdict', [ + (['Ubuntu 24.04 LTS btest01 tty1', 'btest01 login:'], 'pass'), + (['Press Ctrl+Alt+Delete to sign in.'], 'pass'), + (['root@appliance:~#'], 'pass'), + (['Your PC ran into a problem and needs to restart.', 'Stop code: INACCESSIBLE_BOOT_DEVICE'], 'fail'), + (['BitLocker recovery', 'Enter the recovery key for this drive'], 'fail'), + (['No bootable device -- insert boot disk and press any key'], 'fail'), + (['grub rescue>'], 'fail'), + (['You are in emergency mode. After logging in, type "journalctl -xb"'], 'fail'), + (['[ OK ] Started Network Manager.', '[ OK ] Reached target Basic System.', 'Starting cloud-init...'], 'wait'), +]) +def test_boot_verdict(lines, verdict): + img = Image.new('RGB', (720, 400), (40, 40, 40)) + img.putpixel((5, 5), (250, 250, 250)) # not blank + assert classify.boot_verdict(img, ocr=lambda _i: lines)[0] == verdict + + +def test_a_blank_or_unreadable_screen_means_wait_never_pass(): + assert classify.boot_verdict(Image.new('RGB', (720, 400)), ocr=lambda _i: ['login:'])[0] == 'wait' + img = Image.new('RGB', (720, 400), (40, 40, 40)); img.putpixel((5, 5), (250, 250, 250)) + + def broken(_i): + raise classify.OCRFailed('tesseract died') + assert classify.boot_verdict(img, ocr=broken)[0] == 'wait' + assert classify.boot_verdict(img, use_ocr=False)[0] == 'wait' diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 193a015..994d5d2 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -1254,7 +1254,7 @@ def test_support_bundle_route_needs_the_token(tmp_path): r = c.get('/support/bundle', headers={'Authorization': 'Bearer t0k'}) assert r.status_code == 200 and r.mimetype == 'application/zip' and 'attachment; filename="hcm-proxy-' in r.headers['Content-Disposition'] assert r.data[:2] == b'PK' - assert P.identity.VERSION == '0.5.7' + assert P.identity.VERSION == '0.6.0' def test_the_proxy_keeps_a_rotating_log_file(tmp_path): @@ -1385,3 +1385,58 @@ def test_proxy_vm_keeps_kernel_errors_off_its_console(tmp_path): assert f.read_text() == '7 4 1 7' f.write_text('2 4 1 7') assert hostcfg.quiet_kernel_console(str(f), tls='auto') == ('2 4 1 7', '2 4 1 7'), 'an already quieter console is left alone' + + +# ------------------------------------------------------------------ netcheck (test restores, T2) +def _netcheck(): + saved = sys.modules.pop('netcheck', None) + sys.path.insert(0, _PROXY) + try: + return importlib.import_module('netcheck') + finally: + sys.path.remove(_PROXY) + sys.modules.pop('netcheck', None) + if saved: + sys.modules['netcheck'] = saved + + +def _sysnet(tmp_path, ifaces): + d = tmp_path / 'net' + for name, mac in ifaces.items(): + (d / name).mkdir(parents=True) + (d / name / 'address').write_text(mac + '\n') + return str(d) + + +def test_netcheck_binds_everything_to_the_test_nic_and_cleans_up(tmp_path): + nc = _netcheck() + sysnet = _sysnet(tmp_path, {'lo': '00:00:00:00:00:00', 'ens3': '7c:4c:58:00:00:01', 'ens4': '7c:4c:58:00:00:99'}) + calls, probes = [], [] + res = nc.run('7C:4C:58:00:00:99', '172.16.0.250/25', [{'ip': '172.16.0.12', 'ports': [3389, 445]}], settle_s=0, + ping_fn=lambda ip, dev: probes.append(('ping', ip, dev)) or False, + tcp_fn=lambda ip, port, dev: probes.append(('tcp', ip, port, dev)) or port == 3389, + ip_fn=lambda *a: calls.append(a), sys_net=sysnet) + assert res['interface'] == 'ens4' and res['results'] == {'172.16.0.12': {'ping': False, 'ports': {3389: True, 445: False}}} + assert all(p[-1] == 'ens4' for p in probes), 'never through the management NIC (a restored VM keeps its production IP)' + assert calls[:3] == [('link', 'set', 'ens4', 'up'), ('addr', 'add', '172.16.0.250/32', 'dev', 'ens4'), + ('route', 'replace', '172.16.0.12/32', 'dev', 'ens4', 'src', '172.16.0.250')] + assert calls[-3:] == [('route', 'del', '172.16.0.12/32', 'dev', 'ens4'), ('addr', 'del', '172.16.0.250/32', 'dev', 'ens4'), + ('link', 'set', 'ens4', 'down')], 'the probe address and routes go again' + + +def test_netcheck_refuses_without_the_nic_or_with_a_bad_probe(tmp_path): + nc = _netcheck() + sysnet = _sysnet(tmp_path, {'eth0': '02:42:ac:11:00:02'}) # bridge network: only the container's veth + with pytest.raises(nc.NetcheckError, match='host networking'): + nc.run('7c:4c:58:00:00:99', '172.16.0.250/25', [], ip_fn=lambda *a: None, sys_net=sysnet) + with pytest.raises(nc.NetcheckError, match='prefix'): + nc.parse_probe('172.16.0.250/32') + with pytest.raises(nc.NetcheckError): + nc.parse_probe('not-an-ip') + + +def test_host_network_is_detected_from_the_host_interfaces(tmp_path): + nc = _netcheck() + host = _sysnet(tmp_path / 'h', {'ens3': 'aa', 'docker0': 'bb', 'lo': 'cc'}) + assert nc.host_network(_sysnet(tmp_path / 'c1', {'ens3': 'aa', 'lo': 'cc'}), host) is True + assert nc.host_network(_sysnet(tmp_path / 'c2', {'eth0': 'dd', 'lo': 'cc'}), host) is False From b52e0fe5976e1d3eeb5ae8807ecea2ad21728bd7 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sat, 21 Nov 2026 22:52:59 +0100 Subject: [PATCH 2/7] fix: network tests serve DHCP on the test VLAN; failed fulls and post-restart sweep no longer eat backups - Test restores, network level: the proxy serves the test VM its source addresses by DHCP on the test VLAN (dnsmasq, static leases for the test VM's MACs only, no pool/router/DNS) and probes until the VM answers or the timeout; the test VM is started once the leases are served. Proxy 0.6.1: netcheck no longer rejected for lacking a backup target; dnsmasq-base in the image. - A failed run that had started a new chain removes its partial files from the share and the empty chain (two failed fulls of a 28 GB VM filled the lab share). - The clone sweep shortly after a restart skips chains whose backup is running (it deleted the clones of a backup that had just started). --- backup/incremental.py | 28 +++++++++++ backup/testrestore.py | 51 +++++++++++++++----- docs/CHANGELOG.md | 16 +++++-- docs/manual/05-backup.md | 5 +- proxy/Dockerfile | 4 +- proxy/api.py | 2 +- proxy/identity.py | 2 +- proxy/jobs.py | 8 ++-- proxy/netcheck.py | 81 ++++++++++++++++++++++++++------ tests/test_backup_incremental.py | 32 +++++++++++++ tests/test_backup_testrestore.py | 10 +++- tests/test_proxy.py | 46 ++++++++++++++++-- 12 files changed, 241 insertions(+), 44 deletions(-) diff --git a/backup/incremental.py b/backup/incremental.py index bef0887..10aec6f 100644 --- a/backup/incremental.py +++ b/backup/incremental.py @@ -451,9 +451,34 @@ def run_incremental(plan_id: int, policy_id: int | None = None, occurrence=None, except (IncrementalError, HyperCoreError, ProxyError) as e: db.update_run(run_id, status='ERROR', message=str(e), finished_at=_now()) log.error('[run %s] %s', run_id, e) + discard_empty_chain(run_id) except Exception as e: # noqa: BLE001 — never kill the scheduler thread db.update_run(run_id, status='ERROR', message=f'Unexpected error: {e}', finished_at=_now()) log.exception('[run %s] unexpected error', run_id) + discard_empty_chain(run_id) + + +def discard_empty_chain(run_id: int) -> bool: + """A failed run that had started a new chain (a full) leaves partial files on the share and a chain without + points: remove both, or every failed full eats share space until the share is full (live 2026-11-21: two + failed fulls of a 28 GB VM filled the lab share). A chain with any point is never touched.""" + try: + r = db.get_run(run_id) + chain = db.get_chain(r['chain_id']) if r and r.get('chain_id') else None + if not chain or chain.get('status') == 'deleted' or db.get_points(chain['id'], include_pruned=True): + return False + share = db.get_share(chain['target_id'], with_secret=True) if chain.get('target_id') else None + if share: + pc = proxy_client_for(pick_proxy(chain['cluster_id'])) + pc.wait(pc.submit('delete_chain', {'target': {'uri': share['uri_base'], 'username': share.get('username'), + 'password': share.get('password')}, 'chain_dir': chain['chain_dir']}), + timeout=3600) + db.update_chain(chain['id'], status='deleted') + log.info('[run %s] partial data of the failed full removed from the share (%s)', run_id, chain['chain_dir']) + return True + except Exception as e: # noqa: BLE001 — the run's own error is what matters + log.warning('[run %s] partial data of the failed run not removed: %s', run_id, e) + return False def _run(plan: dict, run_id: int, hc: HyperCoreClient | None = None, work_started: datetime | None = None, @@ -752,6 +777,9 @@ def sweep_cluster(cluster_id: str, max_age_days: int = 30) -> dict: for ch in db.chains_with_clones(): if ch['cluster_id'] != cluster_id: continue + if db.plan_run_active(ch.get('plan_id')): + # a run that is going on holds these clones (the sweep after a restart once deleted them mid-copy) + continue _delete_clones(hc, list(ch.get('active_clones') or [])) db.update_chain(ch['id'], active_clones=[]) out['clones'] += len(ch.get('active_clones') or []) diff --git a/backup/testrestore.py b/backup/testrestore.py index 1f392e3..b34ef31 100644 --- a/backup/testrestore.py +++ b/backup/testrestore.py @@ -237,7 +237,7 @@ def __init__(self, verdict: str, detail: str): def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, clock=time.monotonic) -> str: """One test, start to clean-up. Returns the final status.""" rid = run['id'] - state = {'restored': None, 'png': None} + state = {'restored': None, 'png': None, 'netjob': None} status, verdict, detail, checks = 'error', None, None, None try: src = jobs.client_for(run['cluster_id']) @@ -257,14 +257,21 @@ def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, if net: probe_proxy = network_ready(hc, target, plan) # raises Fail with what is missing restored = restore(run, plan, target, point, net, state) - verdict, detail = watch_boot(hc, target, restored, int(plan['timeout_minutes']) * 60, state, sleep=sleep, clock=clock) + timeout_s = int(plan['timeout_minutes']) * 60 + if net: + # the proxy serves the VM's addresses by DHCP and keeps probing while the VM boots + state['netjob'] = start_network_checks(hc, run, plan, restored, source_vm, probe_proxy, point, timeout_s + 300) + t = hc.vm_action(restored, 'START') + if t: + incremental.wait_task(hc, t, 'start test VM', 600) + verdict, detail = watch_boot(hc, target, restored, timeout_s, state, sleep=sleep, clock=clock) db.update_test_run(rid, booted_at=_now()) if net: - checks = network_checks(hc, run, plan, restored, source_vm, probe_proxy, point) + checks = finish_network_checks(state.pop('netjob'), timeout_s + 600) ok, why = judge_checks(checks) if not ok: raise Fail('network', why) - detail = f'{detail}; network checks passed' + detail = f'{detail}; {why}' status = 'passed' except Skip as e: status, detail = 'skipped', str(e) @@ -276,6 +283,11 @@ def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, log.exception('test %s failed unexpectedly', rid) status, detail = 'error', f'unexpected error: {e}'[:1000] finally: + if state.get('netjob'): # the boot check failed: stop probing + try: + state['netjob'][0].cancel(state['netjob'][1]) + except Exception: # noqa: BLE001 + pass keep = None if status == 'failed' and plan.get('keep_failed_hours') and state['restored']: keep = _now() + timedelta(hours=int(plan['keep_failed_hours'])) @@ -296,7 +308,8 @@ def restore(run: dict, plan: dict, target: str, point: dict, net: bool, state: d import restore as restore_mod chain = db.get_chain(point['chain_id']) name = f"{(run.get('vm_name') or 'vm')[:40]}{NAME_MARK}{run['id']}" - params = {'mac_policy': 'new', 'start': True, 'verify': False, 'nic_connected': net, 'extra_tags': [TAG], + # a network test starts the VM itself, once the proxy serves its DHCP leases on the test VLAN + params = {'mac_policy': 'new', 'start': not net, 'verify': False, 'nic_connected': net, 'extra_tags': [TAG], 'description': f"HCM test restore #{run['id']} of {run.get('vm_name')} (point {point['created_at']:%Y-%m-%d %H:%M} UTC); " 'deleted automatically'} if net: @@ -413,20 +426,34 @@ def _is_proxy(vm: dict) -> bool: return 'hcm-proxy' in (vm.get('tags') or '').split(',') -def network_checks(hc, run: dict, plan: dict, vm_uuid: str, source_vm: dict | None, proxy: dict, point: dict) -> list[dict]: - """Ping and port checks of the test VM's addresses through the proxy's test NIC.""" - ips = _ips(hc.get_vm(vm_uuid)) or _ips(source_vm or {}) or _ips(point.get('definition') or {}) +def start_network_checks(hc, run: dict, plan: dict, vm_uuid: str, source_vm: dict | None, proxy: dict, point: dict, + wait_s: float) -> tuple: + """Start the proxy's netcheck job: DHCP leases for the test VM's NICs (each gets the address its source NIC + has), then ping/port probes until the VM answers or wait_s is up. Returns (proxy client, job id).""" + new_nics = hc.get_vm(vm_uuid).get('netDevs') or [] + src_nics = (source_vm or {}).get('netDevs') or (point.get('definition') or {}).get('netDevs') or [] blocked = _infrastructure(proxy, point) - ips = [ip for ip in ips if ip not in blocked] + leases, ips = [], [] + for new, old in zip(new_nics, src_nics): + addr = next((ip for ip in old.get('ipv4Addresses') or [] if ip and not ip.startswith(('127.', '169.254.'))), None) + if addr and addr not in blocked and new.get('macAddress'): + leases.append({'mac': new['macAddress'], 'ip': addr}) + ips.append(addr) if not ips: - raise Fail('network', 'no IPv4 address known for the VM (no guest agent report, none recorded): nothing to check') + raise Fail('network', 'no IPv4 address known for the VM (its source reports none and none was recorded): nothing to check') member = next((m for m in db.test_plan_vms(plan['id']) if m['cluster_id'] == run['cluster_id'] and m['vm_uuid'] == run['vm_uuid']), None) ports = (member or {}).get('ports') ports = list(plan.get('default_ports') or []) if ports is None else ports full = db.get_proxy(proxy['id'], with_secret=True) or proxy pc = incremental.proxy_client_for(full) - job = pc.submit('netcheck', {'mac': proxy['test_mac'], 'probe': plan['probe_address'], 'targets': [{'ip': ip, 'ports': ports} for ip in ips]}) - res = pc.wait(job, timeout=300)['result'] or {} + job = pc.submit('netcheck', {'mac': proxy['test_mac'], 'probe': plan['probe_address'], 'dhcp': leases, 'wait_s': wait_s, + 'targets': [{'ip': ip, 'ports': ports} for ip in ips]}) + return pc, job + + +def finish_network_checks(netjob: tuple, timeout_s: float) -> list[dict]: + pc, job = netjob + res = pc.wait(job, timeout=timeout_s)['result'] or {} return [{'ip': ip, 'ping': r.get('ping'), 'ports': r.get('ports') or {}} for ip, r in (res.get('results') or {}).items()] diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3094303..556a158 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -19,14 +19,22 @@ All notable changes to this project are documented here. The format follows VMs without a guest agent are marked *agentless: screen check only*. - **Network test**: NICs on an isolated test VLAN (refused when another VM on the target cluster uses it), then ping and TCP port checks from a proxy NIC on that VLAN (proxy job `netcheck`, bound to that NIC so a restored - VM's production IP never reaches the production VM). HCM never touches the test VLAN. + VM's production IP never reaches the production VM). The proxy serves the test VM its source addresses by DHCP + on the test VLAN (static leases for the test VM's MACs only) and probes until it answers. HCM never touches + the test VLAN. - Options, off by default: keep a failed test VM for N hours; a byte budget per round. - Results under Runs → **Test restores** (verdict, target, point age, restore and boot time, checks, screenshot) and a **Tested** column on the restore points. A failed test and a fixed VM without a passed test for twice the interval raise a badge on the cluster card and a mail to the closest administrator. -- **Proxy deploy: Test VLAN** adds a second NIC for the network checks. Proxy **0.6.0**: job `netcheck`, - `iproute2` and `iputils-ping` in the image; proxies deployed from now on run with host networking (older ones - show *network tests: redeploy*). +- **Proxy deploy: Test VLAN** adds a second NIC for the network checks. Proxy **0.6.1**: job `netcheck`, + `iproute2`, `iputils-ping` and `dnsmasq-base` in the image; proxies deployed from now on run with host networking + (older ones show *network tests: redeploy*). + +### Fixed +- **A backup that started within two minutes of a restart lost its disk clones.** The clean-up of clones left by + interrupted runs runs shortly after every (re)start of the backup service and also deleted the clones of a run + that had just begun (`No such file or directory: /dev/disk/by-id/virtio-…`). It now skips chains whose backup + is running. ## [1.6.0] diff --git a/docs/manual/05-backup.md b/docs/manual/05-backup.md index 152be12..88a1b0b 100644 --- a/docs/manual/05-backup.md +++ b/docs/manual/05-backup.md @@ -152,7 +152,10 @@ A **test plan** (Backup → Schedules → **Test restores**) belongs to the fold - **Network test (test VLAN)**: the NICs go onto an isolated **test VLAN**, and after the boot check a proxy pings the VM and tries its ports (per VM, or the plan's default; without ports only ping counts, and Windows answers no ping by default). The checks run from a **proxy NIC on the test VLAN**, with the plan's **probe - address** (a free address in the VMs' subnet, with prefix): HCM itself never touches the test VLAN. Restored + address** (a free address in the VMs' subnet, with prefix): HCM itself never touches the test VLAN. A test VLAN + usually has no DHCP, so during the check the proxy hands the test VM, by DHCP, the address its source VM has + (one static lease per test-VM MAC address, no pool: nothing else on the VLAN gets an address), and it keeps + probing until the VM answers or the time is up. Restored VMs keep their addresses and names, so HCM refuses a VLAN that any other VM on the target cluster uses; whether the VLAN is routed elsewhere it cannot see, so keep it isolated on the switches too. The proxy needs to be deployed with 1.7.0 or later (it runs with host networking) and with a **Test VLAN** NIC (Settings → Backup → diff --git a/proxy/Dockerfile b/proxy/Dockerfile index abc5774..fdc9d60 100644 --- a/proxy/Dockerfile +++ b/proxy/Dockerfile @@ -3,9 +3,9 @@ FROM python:3.12-slim-bookworm # qemu-utils: qemu-img / qemu-nbd; cifs-utils + nfs-common: mounting backup targets; # util-linux: blockdev/sfdisk/losetup; udev: udevadm settle; lvm2 + dmsetup: file-level recovery # (COW overlays, LVM import); ntfs-3g: NTFS fallback; genisoimage: ISO delivery; procps: ps/free for -# the support bundle; tini: PID 1 (see below); iproute2 + iputils-ping: network checks of test restores +# the support bundle; tini: PID 1 (see below); iproute2 + iputils-ping + dnsmasq-base: network checks of test restores (DHCP on the test VLAN) RUN apt-get update \ - && apt-get install -y --no-install-recommends qemu-utils cifs-utils nfs-common util-linux fdisk udev lvm2 dmsetup cryptsetup-bin ntfs-3g genisoimage openssl procps tini iproute2 iputils-ping \ + && apt-get install -y --no-install-recommends qemu-utils cifs-utils nfs-common util-linux fdisk udev lvm2 dmsetup cryptsetup-bin ntfs-3g genisoimage openssl procps tini iproute2 iputils-ping dnsmasq-base \ && rm -rf /var/lib/apt/lists/* WORKDIR /app diff --git a/proxy/api.py b/proxy/api.py index ee52587..c3ba575 100644 --- a/proxy/api.py +++ b/proxy/api.py @@ -124,7 +124,7 @@ def submit(kind): missing = [k for k in _REQUIRED[kind] if k not in body] if missing: return jsonify({'error': f'missing fields: {", ".join(missing)}'}), 400 - if not isinstance(body.get('target'), dict) or 'uri' not in body['target']: + if 'target' in _REQUIRED[kind] and (not isinstance(body.get('target'), dict) or 'uri' not in body['target']): return jsonify({'error': 'target.uri is required'}), 400 job = engine.submit(kind, body) log.info('job submitted', extra={'job': job.id, 'kind': kind}) diff --git a/proxy/identity.py b/proxy/identity.py index 88eba08..2d86fdd 100644 --- a/proxy/identity.py +++ b/proxy/identity.py @@ -9,7 +9,7 @@ import socket import subprocess -VERSION = '0.6.0' +VERSION = '0.6.1' _SKIP_PREFIXES = ('lo', 'docker', 'veth', 'br-', 'virbr', 'cni', 'flannel', 'tun', 'tap', 'wg') diff --git a/proxy/jobs.py b/proxy/jobs.py index 923e192..eb3c19c 100644 --- a/proxy/jobs.py +++ b/proxy/jobs.py @@ -308,13 +308,15 @@ def prog(n, _b=done): # ---------------------------------------------------------------- netcheck def run_netcheck(self, job: Job) -> dict: - """request: {mac: the test NIC's MAC, probe: '172.16.0.250/25', targets: [{ip, ports: [int]}]}. - Ping and TCP checks of a test-restored VM on the test VLAN, through the test NIC only (netcheck.py).""" + """request: {mac: the test NIC's MAC, probe: '172.16.0.250/25', targets: [{ip, ports: [int]}], + dhcp?: [{mac, ip}], wait_s?}. Ping and TCP checks of a test-restored VM on the test VLAN, through the test + NIC only, repeated until it answers or wait_s is up, serving its static DHCP leases meanwhile (netcheck.py).""" import netcheck req = job.request job.progress = {'targets': len(req.get('targets') or [])} try: - return netcheck.run(req['mac'], req['probe'], req.get('targets') or []) + return netcheck.run(req['mac'], req['probe'], req.get('targets') or [], dhcp=req.get('dhcp') or None, + wait_s=float(req.get('wait_s') or 0), cancelled=job.cancelled) except netcheck.NetcheckError as e: raise RuntimeError(str(e)) from None diff --git a/proxy/netcheck.py b/proxy/netcheck.py index 40b95d9..ccf87dc 100644 --- a/proxy/netcheck.py +++ b/proxy/netcheck.py @@ -8,8 +8,12 @@ A restored VM keeps its production IP address, and the proxy's management NIC may well sit in the same subnet. A plain connect would then leave through the management NIC and could reach the *production* VM: a false pass. So every probe is bound to the test NIC (SO_BINDTODEVICE for TCP, `ping -I` for ICMP), the probe address is -added as a /32 (no subnet route that could compete with the management NIC's), and each target gets a host -route through the test NIC for the duration of the check. The caller refuses targets that are the proxy's own +added with `noprefixroute` (no subnet route that could compete with the management NIC's), and each target gets +a host route through the test NIC for the duration of the check. + +The test VLAN usually has no DHCP server, and a VM configured for DHCP would come up without an address there. +So the proxy can serve DHCP on the test NIC during the check: dnsmasq with one static lease per test-VM MAC (the +address its source NIC has), no pool, no router, no DNS: nothing else on the VLAN gets an address. The caller refuses targets that are the proxy's own infrastructure (its gateway, the share, HyperCore Manager), so those routes never cut the proxy off. Needs the proxy container to run in the host's network namespace (`--network host`, proxies deployed from @@ -96,9 +100,38 @@ def tcp(ip: str, port: int, dev: str, timeout: float = 3.0) -> bool: s.close() +def answered(results: dict) -> bool: + """One target answers on every port asked for (with no ports asked for: answers ping).""" + for r in results.values(): + ports = r.get('ports') or {} + if (ports and all(ports.values())) or (not ports and r.get('ping')): + return True + return False + + +def dnsmasq_cmd(dev: str, probe: ipaddress.IPv4Interface, leases: list[dict]) -> list[str]: + """DHCP for the test VM only: a static lease per MAC (its source NIC's address), no pool, no DNS, no router. + Nothing else on the VLAN gets an address.""" + cmd = ['dnsmasq', '--no-daemon', '--port=0', f'--interface={dev}', '--bind-interfaces', '--except-interface=lo', + '--dhcp-authoritative', '--leasefile-ro', '--dhcp-option=3', '--dhcp-option=6', '--log-dhcp'] + nets = set() + for l in leases: + a = ipaddress.IPv4Address(str(l['ip'])) + net = ipaddress.IPv4Network(f'{a}/{probe.network.prefixlen}', strict=False) + if net not in nets: + cmd.append(f'--dhcp-range={net.network_address},static,{net.netmask},1h') + nets.add(net) + cmd.append(f"--dhcp-host={str(l['mac']).lower()},{a},infinite") + return cmd + + def run(mac: str, probe: str, targets: list[dict], settle_s: float = 3.0, ping_fn=ping, tcp_fn=tcp, ip_fn=_ip, - sys_net: str = SYS_NET) -> dict: - """targets: [{ip, ports: [int]}]. Returns {'interface', 'results': {ip: {'ping': bool, 'ports': {port: bool}}}}.""" + sys_net: str = SYS_NET, dhcp: list[dict] | None = None, wait_s: float = 0, interval_s: float = 10, + cancelled=None, popen=subprocess.Popen, sleep=time.sleep, clock=time.monotonic) -> dict: + """targets: [{ip, ports: [int]}]. With wait_s, probe every interval_s until a target answers (the VM is still + booting) or the time is up. dhcp: [{mac, ip}] serves those static leases on the test VLAN meanwhile (a VM + configured for DHCP gets its own address; the test VLAN has no DHCP server of its own). + Returns {'interface', 'probe', 'results': {ip: {'ping': bool, 'ports': {port: bool}}}, 'answered', 'after_s'}.""" dev = interface_for_mac(mac, sys_net) if not dev: raise NetcheckError(f'no interface with MAC {mac} in the proxy: it needs a NIC on the test VLAN and must run ' @@ -111,27 +144,45 @@ def run(mac: str, probe: str, targets: list[dict], settle_s: float = 3.0, ping_f except (KeyError, ValueError): raise NetcheckError(f"not an IPv4 address: {t.get('ip')!r}") from None ip_fn('link', 'set', dev, 'up') - ip_fn('addr', 'add', f'{pr.ip}/32', 'dev', dev) - routes = [] + # with its prefix but without the subnet route: dnsmasq needs to see the subnet on the interface, the + # management NIC (often in the same subnet) must keep the route + ip_fn('addr', 'add', f'{pr.ip}/{pr.network.prefixlen}', 'dev', dev, 'noprefixroute') + routes, server = [], None + t0 = clock() try: for a in cleaned: - # a host route per target through the test NIC, for the few seconds of the check: the management - # NIC's subnet route stays, but this address is reached on the test VLAN only + # a host route per target through the test NIC, for the duration of the check only ip_fn('route', 'replace', f'{a}/32', 'dev', dev, 'src', str(pr.ip)) routes.append(a) - time.sleep(settle_s) # link up, switch learns the port - results = {} - for t in targets: - ip = str(t['ip']) - results[ip] = {'ping': ping_fn(ip, dev), 'ports': {int(p): tcp_fn(ip, int(p), dev) for p in t.get('ports') or []}} - return {'interface': dev, 'probe': str(pr.ip), 'results': results} + if dhcp: + server = popen(dnsmasq_cmd(dev, pr, dhcp), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + sleep(settle_s) # link up, switch learns the port + while True: + results = {} + for t in targets: + ip = str(t['ip']) + results[ip] = {'ping': ping_fn(ip, dev), 'ports': {int(p): tcp_fn(ip, int(p), dev) for p in t.get('ports') or []}} + ok = answered(results) + if ok or clock() - t0 >= wait_s or (cancelled and cancelled()): + return {'interface': dev, 'probe': str(pr.ip), 'results': results, 'answered': ok, + 'after_s': round(clock() - t0, 1), 'dhcp': bool(dhcp)} + sleep(interval_s) finally: + if server is not None: + try: + server.terminate() + server.wait(timeout=10) + except Exception: # noqa: BLE001 + try: + server.kill() + except Exception: # noqa: BLE001 + pass for a in routes: try: ip_fn('route', 'del', f'{a}/32', 'dev', dev) except NetcheckError: pass - for args in (('addr', 'del', f'{pr.ip}/32', 'dev', dev), ('link', 'set', dev, 'down')): + for args in (('addr', 'del', f'{pr.ip}/{pr.network.prefixlen}', 'dev', dev), ('link', 'set', dev, 'down')): try: ip_fn(*args) except NetcheckError: diff --git a/tests/test_backup_incremental.py b/tests/test_backup_incremental.py index 38bb024..a205223 100644 --- a/tests/test_backup_incremental.py +++ b/tests/test_backup_incremental.py @@ -757,3 +757,35 @@ def relocate(proxy, hc=None): assert inc.ensure_reachable({**_MOVED_PROXY, 'url': 'https://172.16.0.80:8083'})['url'] == 'https://172.16.0.80:8083' monkeypatch.setattr(inc, 'relocate_proxy', lambda *a, **k: (_ for _ in ()).throw(RuntimeError('boom'))) assert inc.ensure_reachable(dict(_MOVED_PROXY))['url'] == 'https://172.16.0.65:8083', 'a failed lookup never breaks the run' + + +def test_the_sweep_leaves_the_clones_of_a_running_backup_alone(world, monkeypatch): + """Live 2026-11-21: the sweep two minutes after a restart deleted the clones of a backup that had just started.""" + hc = _CdHC(running=True) + deleted = [] + monkeypatch.setattr(inc.jobs, 'client_for', lambda cid: hc) + monkeypatch.setattr(inc, '_delete_clones', lambda h, uuids: deleted.extend(uuids)) + monkeypatch.setattr(world.db, 'chains_with_clones', lambda: [ + {'id': 1, 'cluster_id': 'c1', 'plan_id': 5, 'active_clones': ['busy-clone']}, + {'id': 2, 'cluster_id': 'c1', 'plan_id': 6, 'active_clones': ['left-behind']}], raising=False) + monkeypatch.setattr(world.db, 'plan_run_active', lambda pid: pid == 5, raising=False) + monkeypatch.setattr(world.db, 'update_chain', lambda *a, **k: None, raising=False) + assert inc.sweep_cluster('c1')['clones'] == 1 + assert deleted == ['left-behind'] + + +def test_a_failed_full_removes_its_partial_data_but_never_a_chain_with_points(world, monkeypatch): + """Live 2026-11-21: two failed fulls of a 28 GB VM left their partial files on the share until it was full.""" + db = world.db + empty = db.add_chain(db.plan, 9, 'Lab', 'Lab/w11_1.chain') + good = db.add_chain(db.plan, 9, 'Lab', 'Lab/w11_0.chain') + db.add_point(good, 0, 'full', 'base', {}, 4, 4 << 20, 1.0, [], {}, 1) + runs = {1: {'id': 1, 'chain_id': empty}, 2: {'id': 2, 'chain_id': good}} + monkeypatch.setattr(db, 'get_run', lambda rid: runs.get(rid), raising=False) + updated = {} + monkeypatch.setattr(db, 'update_chain', lambda cid, **f: updated.setdefault(cid, {}).update(f), raising=False) + assert inc.discard_empty_chain(1) is True + assert world.pc.jobs[-1] == ('delete_chain', {'target': {'uri': 'smb://nas/share', 'username': 'u', 'password': 'p'}, 'chain_dir': 'Lab/w11_1.chain'}) + assert updated[empty] == {'status': 'deleted'} + n = len(world.pc.jobs) + assert inc.discard_empty_chain(2) is False and len(world.pc.jobs) == n and good not in updated diff --git a/tests/test_backup_testrestore.py b/tests/test_backup_testrestore.py index 7049532..48ddb39 100644 --- a/tests/test_backup_testrestore.py +++ b/tests/test_backup_testrestore.py @@ -241,10 +241,16 @@ def submit(self, kind, body): sent.append((kind, body)); return 'j1' def wait(self, j, timeout=0): return {'result': {'results': {'10.0.0.5': {'ping': False, 'ports': {3389: True}}}}} monkeypatch.setattr(tr.incremental, 'proxy_client_for', lambda p: PC()) + world.tgt.boot = [dict(b, netDevs=[{'vlan': 999, 'macAddress': '7C:4C:58:AA:BB:CC'}]) for b in world.tgt.boot] c = Clock() assert tr.run_test(RUN, NET, 'dr', POINT, sleep=c.sleep, clock=c) == 'passed' - assert world.db.restores[1]['params']['vlan'] == 999 and world.db.restores[1]['params']['nic_connected'] is True - assert sent == [('netcheck', {'mac': '7C:4C:58:00:00:99', 'probe': '10.0.0.250/24', 'targets': [{'ip': '10.0.0.5', 'ports': [3389]}]})] + params = world.db.restores[1]['params'] + assert params['vlan'] == 999 and params['nic_connected'] is True and params['start'] is False, 'started after the DHCP leases' + assert ('START', 'restored') in world.tgt.actions + kind, body = sent[0] + assert kind == 'netcheck' and body['mac'] == '7C:4C:58:00:00:99' and body['probe'] == '10.0.0.250/24' + assert body['dhcp'] == [{'mac': '7C:4C:58:AA:BB:CC', 'ip': '10.0.0.5'}], 'the test VM gets its source address by DHCP' + assert body['targets'] == [{'ip': '10.0.0.5', 'ports': [3389]}] and body['wait_s'] == 900 assert world.db.runs[1]['checks'] == [{'ip': '10.0.0.5', 'ping': False, 'ports': {3389: True}}] diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 994d5d2..3851745 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -1254,7 +1254,7 @@ def test_support_bundle_route_needs_the_token(tmp_path): r = c.get('/support/bundle', headers={'Authorization': 'Bearer t0k'}) assert r.status_code == 200 and r.mimetype == 'application/zip' and 'attachment; filename="hcm-proxy-' in r.headers['Content-Disposition'] assert r.data[:2] == b'PK' - assert P.identity.VERSION == '0.6.0' + assert P.identity.VERSION == '0.6.1' def test_the_proxy_keeps_a_rotating_log_file(tmp_path): @@ -1418,12 +1418,39 @@ def test_netcheck_binds_everything_to_the_test_nic_and_cleans_up(tmp_path): ip_fn=lambda *a: calls.append(a), sys_net=sysnet) assert res['interface'] == 'ens4' and res['results'] == {'172.16.0.12': {'ping': False, 'ports': {3389: True, 445: False}}} assert all(p[-1] == 'ens4' for p in probes), 'never through the management NIC (a restored VM keeps its production IP)' - assert calls[:3] == [('link', 'set', 'ens4', 'up'), ('addr', 'add', '172.16.0.250/32', 'dev', 'ens4'), + assert calls[:3] == [('link', 'set', 'ens4', 'up'), ('addr', 'add', '172.16.0.250/25', 'dev', 'ens4', 'noprefixroute'), ('route', 'replace', '172.16.0.12/32', 'dev', 'ens4', 'src', '172.16.0.250')] - assert calls[-3:] == [('route', 'del', '172.16.0.12/32', 'dev', 'ens4'), ('addr', 'del', '172.16.0.250/32', 'dev', 'ens4'), + assert calls[-3:] == [('route', 'del', '172.16.0.12/32', 'dev', 'ens4'), ('addr', 'del', '172.16.0.250/25', 'dev', 'ens4'), ('link', 'set', 'ens4', 'down')], 'the probe address and routes go again' +def test_netcheck_serves_dhcp_and_waits_until_the_vm_answers(tmp_path): + nc = _netcheck() + sysnet = _sysnet(tmp_path, {'ens4': '7c:4c:58:00:00:99'}) + answers = iter([False, False, True]) + servers = [] + + class Srv: + def __init__(self, cmd, **kw): self.cmd = cmd; self.stopped = False; servers.append(self) + def terminate(self): self.stopped = True + def wait(self, timeout=None): return 0 + t = [0.0] + res = nc.run('7c:4c:58:00:00:99', '172.16.0.126/25', [{'ip': '172.16.0.52', 'ports': [22]}], settle_s=0, + ping_fn=lambda ip, dev: True, tcp_fn=lambda ip, port, dev: next(answers), ip_fn=lambda *a: None, sys_net=sysnet, + dhcp=[{'mac': '7C:4C:58:AA:BB:CC', 'ip': '172.16.0.52'}], wait_s=600, interval_s=10, popen=Srv, + sleep=lambda s: t.__setitem__(0, t[0] + s), clock=lambda: t[0]) + assert res['answered'] and res['after_s'] == 20 and res['results']['172.16.0.52']['ports'] == {22: True} + cmd = servers[0].cmd + assert '--dhcp-host=7c:4c:58:aa:bb:cc,172.16.0.52,infinite' in cmd and '--dhcp-range=172.16.0.0,static,255.255.255.128,1h' in cmd + assert '--interface=ens4' in cmd and '--port=0' in cmd and '--dhcp-option=3' in cmd, 'only the test NIC, no DNS, no router' + assert servers[0].stopped, 'the DHCP server stops with the check' + t[0] = 0.0 + res = nc.run('7c:4c:58:00:00:99', '172.16.0.126/25', [{'ip': '172.16.0.52', 'ports': [22]}], settle_s=0, + ping_fn=lambda ip, dev: True, tcp_fn=lambda ip, port, dev: False, ip_fn=lambda *a: None, sys_net=sysnet, + wait_s=30, interval_s=10, sleep=lambda s: t.__setitem__(0, t[0] + s), clock=lambda: t[0]) + assert not res['answered'] and res['after_s'] == 30 + + def test_netcheck_refuses_without_the_nic_or_with_a_bad_probe(tmp_path): nc = _netcheck() sysnet = _sysnet(tmp_path, {'eth0': '02:42:ac:11:00:02'}) # bridge network: only the container's veth @@ -1440,3 +1467,16 @@ def test_host_network_is_detected_from_the_host_interfaces(tmp_path): host = _sysnet(tmp_path / 'h', {'ens3': 'aa', 'docker0': 'bb', 'lo': 'cc'}) assert nc.host_network(_sysnet(tmp_path / 'c1', {'ens3': 'aa', 'lo': 'cc'}), host) is True assert nc.host_network(_sysnet(tmp_path / 'c2', {'eth0': 'dd', 'lo': 'cc'}), host) is False + + +def test_a_netcheck_job_needs_no_backup_target(tmp_path): + """Live 2026-11-21: the API demanded target.uri for every job kind; netcheck has none.""" + cfg = P.config.Config(api_token='t0k', data_dir=str(tmp_path / 'data'), backend='file') + submitted = [] + engine = types.SimpleNamespace(backend=P.images.FileBackend(), list=lambda: [], get=lambda i: None, jobs={}, + submit=lambda kind, req: submitted.append(kind) or types.SimpleNamespace(id='j1', state='queued')) + c = P.api.create_app(cfg, engine).test_client() + h = {'Authorization': 'Bearer t0k'} + r = c.post('/jobs/netcheck', json={'mac': 'aa', 'probe': '10.0.0.9/24', 'targets': []}, headers=h) + assert r.status_code in (200, 201, 202) and submitted == ['netcheck'] + assert c.post('/jobs/verify', json={'chain_dir': 'x', 'target': {}}, headers=h).status_code == 400 From 46c8282ecd7f53ff2d773fcb9b102b5893d2d8b0 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sat, 21 Nov 2026 23:39:20 +0100 Subject: [PATCH 3/7] fix: boot check reads a Windows lock screen; backups report the check and checksum phases - Console boot verdict: a second OCR pass for white text (near-white pixels only, sparse mode) when the first decides nothing; a clock line plus a weekday counts as a lock screen. Live: a restored Windows 11 VM's lock screen read '-' before, now passes; also catches white-on-blue stop and BitLocker recovery screens. - Proxy 0.6.2 reports the phases after a disk's copy (image check, checksum read-back with bytes); the run's message shows them instead of sitting at the last MiB. - "guest agent unknown (source VM is off)" instead of "agent unknown (VM is off)", en/nl/de/fr. --- backup/incremental.py | 13 ++++++- console/classify.py | 66 ++++++++++++++++++++++++++------ dashboard/static/lang/de.js | 2 +- dashboard/static/lang/en.js | 2 +- dashboard/static/lang/fr.js | 2 +- dashboard/static/lang/nl.js | 2 +- docs/CHANGELOG.md | 5 ++- proxy/identity.py | 2 +- proxy/jobs.py | 14 ++++++- tests/test_backup_incremental.py | 8 ++++ tests/test_console.py | 15 ++++++-- tests/test_proxy.py | 2 +- 12 files changed, 109 insertions(+), 24 deletions(-) diff --git a/backup/incremental.py b/backup/incremental.py index 10aec6f..f404f62 100644 --- a/backup/incremental.py +++ b/backup/incremental.py @@ -458,6 +458,17 @@ def run_incremental(plan_id: int, policy_id: int | None = None, occurrence=None, discard_empty_chain(run_id) +def backup_progress_text(kind: str, p: dict) -> str: + """'full: 1200/28141 MiB, device 1/3', and after a disk's copy what the proxy does with it (proxy 0.6.2+).""" + total_dev = p.get('devices_total', 1) + text = f'{kind}: {p.get("blocks_done", 0)}/{p["blocks_total"]} MiB, device {min(p.get("devices_done", 0) + 1, total_dev)}/{total_dev}' + if p.get('phase') == 'check': + text += ': checking the image' + elif p.get('phase') == 'checksum': + text += f': checksum {int(p.get("checksum_done") or 0) >> 20}/{int(p.get("checksum_total") or 0) >> 20} MiB' + return text + + def discard_empty_chain(run_id: int) -> bool: """A failed run that had started a new chain (a full) leaves partial files on the share and a chain without points: remove both, or every failed full eats share space until the share is full (live 2026-11-21: two @@ -588,7 +599,7 @@ 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=f'{kind}: {p.get("blocks_done", 0)}/{p["blocks_total"]} MiB, device {min(p.get("devices_done", 0) + 1, total_dev)}/{total_dev}') + db.update_run(run_id, message=backup_progress_text(kind, 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'] diff --git a/console/classify.py b/console/classify.py index e820b67..9e80f14 100644 --- a/console/classify.py +++ b/console/classify.py @@ -211,19 +211,35 @@ def classify(img: Image.Image, refs: Iterable[str] = (), use_ocr: bool = True, o ) -def boot_verdict(img: Image.Image, use_ocr: bool = True, ocr=None) -> tuple[str, str]: - """('pass' | 'fail' | 'wait', detail) for the console of a test-restored VM. Pass: a login prompt, a lock or - sign-in screen, or a shell (auto-login). Fail: a screen that shows the VM is stuck (stop screen, recovery key, - nothing to boot). Anything else (blank, boot logo, log output): wait and look again.""" - ocr = ocr or ocr_lines - if is_blank(img): - return 'wait', 'screen is blank' - if not use_ocr: - return 'wait', 'no OCR available' +_CLOCK = re.compile(r'^\s*\d{1,2}[:.]\d{2}\s*$') +_WEEKDAYS = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', + 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag', 'zondag', + 'montag', 'dienstag', 'mittwoch', 'donnerstag', 'freitag', 'samstag', 'sonntag', + 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche') + + +def ocr_bright(img: Image.Image, timeout: float = 60, threshold: int = 225) -> list[str]: + """Only the near-white pixels, as dark text on white, read as sparse text: white text on a coloured or + photographic background (the Windows lock screen's clock, a stop screen, the BitLocker recovery screen), + which the normal pass cannot separate from the background (measured on a Windows 11 lock screen: the + normal pass read '-', this one '23:36' and 'Saturday, 21 November').""" + g = img.convert('L').point(lambda v: 0 if v > threshold else 255) + buf = io.BytesIO() + g.save(buf, 'PNG') + env = dict(os.environ, OMP_THREAD_LIMIT='1') try: - lines = ocr(img) - except OCRFailed as e: - return 'wait', str(e) + r = subprocess.run(['tesseract', 'stdin', 'stdout', '--psm', '11'], input=buf.getvalue(), + capture_output=True, timeout=timeout, env=env) + except subprocess.TimeoutExpired: + raise OCRFailed(f'text recognition took longer than {timeout:g} s') from None + except OSError as e: + raise OCRFailed(f'text recognition unavailable: {e}') from None + if r.returncode != 0: + raise OCRFailed('text recognition failed: ' + r.stderr.decode('utf-8', 'replace').strip()[:120]) + return [ln.strip() for ln in r.stdout.decode('utf-8', 'replace').splitlines() if ln.strip()] + + +def _judge_boot(lines: list[str]) -> tuple[str, str] | None: flat = _letters(' '.join(lines)) for phrase, what in BOOT_FAIL_PHRASES: if phrase in flat: @@ -233,4 +249,30 @@ def boot_verdict(img: Image.Image, use_ocr: bool = True, ocr=None) -> tuple[str, return 'pass', 'shell prompt (logged in automatically)' if found: return 'pass', found + if any(_CLOCK.match(ln) for ln in lines) and any(d in flat for d in _WEEKDAYS): + return 'pass', 'lock screen (clock and date)' + return None + + +def boot_verdict(img: Image.Image, use_ocr: bool = True, ocr=None, ocr2=None) -> tuple[str, str]: + """('pass' | 'fail' | 'wait', detail) for the console of a test-restored VM. Pass: a login prompt, a lock or + sign-in screen (also a Windows lock screen showing only its clock and date), or a shell (auto-login). Fail: a + screen that shows the VM is stuck (stop screen, recovery key, nothing to boot). Anything else (blank, boot + logo, log output): wait and look again. A second OCR pass for white text runs only when the first decides + nothing.""" + ocr = ocr or ocr_lines + ocr2 = ocr2 or ocr_bright + if is_blank(img): + return 'wait', 'screen is blank' + if not use_ocr: + return 'wait', 'no OCR available' + try: + found = _judge_boot(ocr(img)) + if found: + return found + found = _judge_boot(ocr2(img)) + if found: + return found + except OCRFailed as e: + return 'wait', str(e) return 'wait', 'no login screen yet' diff --git a/dashboard/static/lang/de.js b/dashboard/static/lang/de.js index 633bba8..5f74b00 100644 --- a/dashboard/static/lang/de.js +++ b/dashboard/static/lang/de.js @@ -1776,7 +1776,7 @@ window.LANG = { 'tr.v_screen': "per Bildschirm", 'tr.agentless': "ohne Agent: nur Bildschirmprüfung", 'tr.agentless_hint': "Die VM hat in Produktion keinen Guest-Agent, ein Erfolg beruht also nur auf dem Konsolenbild (eine schwächere Prüfung).", - 'tr.agent_unknown': "Agent unbekannt (VM aus)", + 'tr.agent_unknown': "Guest-Agent unbekannt (Quell-VM aus)", 'tr.on_cluster': "auf {cluster}", 'tr.point_age': "Punkt {h} h alt", 'tr.restore_took': "Wiederherstellung {d}", diff --git a/dashboard/static/lang/en.js b/dashboard/static/lang/en.js index 1c48bd6..fd4fa2d 100644 --- a/dashboard/static/lang/en.js +++ b/dashboard/static/lang/en.js @@ -1777,7 +1777,7 @@ window.LANG = { 'tr.v_screen': "by screen", 'tr.agentless': "agentless: screen check only", 'tr.agentless_hint': "The VM has no guest agent in production, so a pass rests on the console screen alone (a weaker check).", - 'tr.agent_unknown': "agent unknown (VM is off)", + 'tr.agent_unknown': "guest agent unknown (source VM is off)", 'tr.on_cluster': "on {cluster}", 'tr.point_age': "point {h} h old", 'tr.restore_took': "restore {d}", diff --git a/dashboard/static/lang/fr.js b/dashboard/static/lang/fr.js index 7cac319..e7a8b32 100644 --- a/dashboard/static/lang/fr.js +++ b/dashboard/static/lang/fr.js @@ -1776,7 +1776,7 @@ window.LANG = { 'tr.v_screen': "par l'écran", 'tr.agentless': "sans agent : contrôle d'écran seul", 'tr.agentless_hint': "La VM n'a pas d'agent invité en production : une réussite repose sur le seul écran de console (contrôle plus faible).", - 'tr.agent_unknown': "agent inconnu (VM éteinte)", + 'tr.agent_unknown': "agent invité inconnu (VM source éteinte)", 'tr.on_cluster': "sur {cluster}", 'tr.point_age': "point de {h} h", 'tr.restore_took': "restauration {d}", diff --git a/dashboard/static/lang/nl.js b/dashboard/static/lang/nl.js index 002e1b7..db23a0a 100644 --- a/dashboard/static/lang/nl.js +++ b/dashboard/static/lang/nl.js @@ -1776,7 +1776,7 @@ window.LANG = { 'tr.v_screen': "via scherm", 'tr.agentless': "zonder agent: alleen schermcontrole", 'tr.agentless_hint': "De VM heeft in productie geen guest agent, dus een geslaagde test rust alleen op het consolescherm (een zwakkere controle).", - 'tr.agent_unknown': "agent onbekend (VM staat uit)", + 'tr.agent_unknown': "guest agent onbekend (bron-VM staat uit)", 'tr.on_cluster': "op {cluster}", 'tr.point_age': "punt {h} u oud", 'tr.restore_took': "herstel {d}", diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 556a158..a4d1683 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -26,11 +26,14 @@ All notable changes to this project are documented here. The format follows - Results under Runs → **Test restores** (verdict, target, point age, restore and boot time, checks, screenshot) and a **Tested** column on the restore points. A failed test and a fixed VM without a passed test for twice the interval raise a badge on the cluster card and a mail to the closest administrator. -- **Proxy deploy: Test VLAN** adds a second NIC for the network checks. Proxy **0.6.1**: job `netcheck`, +- **Proxy deploy: Test VLAN** adds a second NIC for the network checks. Proxy **0.6.2**: job `netcheck`, `iproute2`, `iputils-ping` and `dnsmasq-base` in the image; proxies deployed from now on run with host networking (older ones show *network tests: redeploy*). ### Fixed +- **A big full looked stuck at its last MiB.** After a disk is copied the proxy checks the image and reads it back + for its checksum, minutes on a large disk, without reporting anything. The run now says so + (`device 1/3: checksum 12000/27000 MiB`). - **A backup that started within two minutes of a restart lost its disk clones.** The clean-up of clones left by interrupted runs runs shortly after every (re)start of the backup service and also deleted the clones of a run that had just begun (`No such file or directory: /dev/disk/by-id/virtio-…`). It now skips chains whose backup diff --git a/proxy/identity.py b/proxy/identity.py index 2d86fdd..0fac1da 100644 --- a/proxy/identity.py +++ b/proxy/identity.py @@ -9,7 +9,7 @@ import socket import subprocess -VERSION = '0.6.1' +VERSION = '0.6.2' _SKIP_PREFIXES = ('lo', 'docker', 'veth', 'br-', 'virbr', 'cni', 'flannel', 'tun', 'tap', 'wg') diff --git a/proxy/jobs.py b/proxy/jobs.py index eb3c19c..28bf4f8 100644 --- a/proxy/jobs.py +++ b/proxy/jobs.py @@ -203,16 +203,28 @@ def run_backup(self, job: Job) -> dict: def prog(done, total, _b=base_done): job.progress['blocks_done'] = _b + done // copier.MiB + job.progress['phase'] = 'copy' with self.backend.prepare(path, size, backing) as writable: written = copier.copy_intervals(src, writable, dev_map, writers=self.cfg.writers, progress=prog, cancelled=job.cancelled) if job.cancelled(): raise RuntimeError('cancelled') + # after the copy: the image is checked and read back once for its checksum. On a big full that + # takes minutes; the phases are reported so the run does not look stuck at its last MiB + job.progress['phase'] = 'check' problem = self.backend.check_detail(path) if problem: raise RuntimeError(f'image check failed: {fname}: {problem}') + job.progress.update(phase='checksum', checksum_done=0, checksum_total=os.path.getsize(path)) + + def hashed(n): + job.progress['checksum_done'] = n + digest = manifest.sha256_file(path, progress=hashed, cancelled=job.cancelled) out_devices.append({'uuid': dev['uuid'], 'type': dev.get('type', 'VIRTIO_DISK'), 'file': fname, 'size': size, 'serial': dev.get('serial'), 'blocks': copier.blocks_in(dev_map), 'bytes_written': written, - 'full': backing is None and kind == 'delta', 'sha256': manifest.sha256_file(path)}) + 'full': backing is None and kind == 'delta', 'sha256': digest}) + job.progress.pop('phase', None) + job.progress.pop('checksum_done', None) + job.progress.pop('checksum_total', None) job.progress['devices_done'] += 1 self._persist(job) point = {'kind': kind, 'seq': seq, 'dir': os.path.basename(point_dir), 'previous_seq': prev_seq, 'created_at': _now(), diff --git a/tests/test_backup_incremental.py b/tests/test_backup_incremental.py index a205223..cf97c01 100644 --- a/tests/test_backup_incremental.py +++ b/tests/test_backup_incremental.py @@ -789,3 +789,11 @@ def test_a_failed_full_removes_its_partial_data_but_never_a_chain_with_points(wo assert updated[empty] == {'status': 'deleted'} n = len(world.pc.jobs) assert inc.discard_empty_chain(2) is False and len(world.pc.jobs) == n and good not in updated + + +def test_backup_progress_says_what_happens_after_the_copy(): + p = {'blocks_done': 28139, 'blocks_total': 28141, 'devices_done': 0, 'devices_total': 3} + assert inc.backup_progress_text('full', p) == 'full: 28139/28141 MiB, device 1/3' + assert inc.backup_progress_text('full', dict(p, phase='check')).endswith(': checking the image') + assert inc.backup_progress_text('full', dict(p, phase='checksum', checksum_done=12 << 30, checksum_total=27 << 30)).endswith( + ': checksum 12288/27648 MiB') diff --git a/tests/test_console.py b/tests/test_console.py index e7c62f4..dfb7fda 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -281,14 +281,23 @@ def test_carries_input_for_read_only_viewers(): def test_boot_verdict(lines, verdict): img = Image.new('RGB', (720, 400), (40, 40, 40)) img.putpixel((5, 5), (250, 250, 250)) # not blank - assert classify.boot_verdict(img, ocr=lambda _i: lines)[0] == verdict + assert classify.boot_verdict(img, ocr=lambda _i: lines, ocr2=lambda _i: [])[0] == verdict def test_a_blank_or_unreadable_screen_means_wait_never_pass(): - assert classify.boot_verdict(Image.new('RGB', (720, 400)), ocr=lambda _i: ['login:'])[0] == 'wait' + assert classify.boot_verdict(Image.new('RGB', (720, 400)), ocr=lambda _i: ['login:'], ocr2=lambda _i: [])[0] == 'wait' img = Image.new('RGB', (720, 400), (40, 40, 40)); img.putpixel((5, 5), (250, 250, 250)) def broken(_i): raise classify.OCRFailed('tesseract died') - assert classify.boot_verdict(img, ocr=broken)[0] == 'wait' + assert classify.boot_verdict(img, ocr=broken, ocr2=lambda _i: [])[0] == 'wait' assert classify.boot_verdict(img, use_ocr=False)[0] == 'wait' + + +def test_a_windows_lock_screen_with_only_its_clock_passes_through_the_white_text_pass(): + """Live 2026-11-21: a restored Windows 11 VM showed only clock and date; the normal OCR pass read '-'.""" + img = Image.new('RGB', (1024, 768), (20, 50, 200)); img.putpixel((5, 5), (250, 250, 250)) + assert classify.boot_verdict(img, ocr=lambda _i: ['-'], ocr2=lambda _i: ['23:36', 'Saturday, 21 November']) == \ + ('pass', 'lock screen (clock and date)') + assert classify.boot_verdict(img, ocr=lambda _i: ['-'], ocr2=lambda _i: ['Your PC ran into a problem'])[0] == 'fail' + assert classify.boot_verdict(img, ocr=lambda _i: ['-'], ocr2=lambda _i: ['12:00'])[0] == 'wait', 'a clock alone is not enough' diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 3851745..c403d6c 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -1254,7 +1254,7 @@ def test_support_bundle_route_needs_the_token(tmp_path): r = c.get('/support/bundle', headers={'Authorization': 'Bearer t0k'}) assert r.status_code == 200 and r.mimetype == 'application/zip' and 'attachment; filename="hcm-proxy-' in r.headers['Content-Disposition'] assert r.data[:2] == b'PK' - assert P.identity.VERSION == '0.6.1' + assert P.identity.VERSION == '0.6.2' def test_the_proxy_keeps_a_rotating_log_file(tmp_path): From f3b407c1acd797fab59a32ee3a2a047b00de4e2a Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sat, 21 Nov 2026 23:54:12 +0100 Subject: [PATCH 4/7] feat(ui): progress bars for running backups, restores and test restores Green while copying or writing, purple while verifying (image check and checksum read-back), sliding when the amount is unknown; a running test restore shows its step (restore, boot against its timeout, network checks, clean-up). Runs, restores and test runs store structured progress (migration 054). Texts in en/nl/de/fr. --- backup/db.py | 16 +++++---- backup/incremental.py | 18 ++++++++-- backup/restore.py | 24 +++++++------ backup/testrestore.py | 7 +++- dashboard/static/index.html | 57 ++++++++++++++++++++++++++++-- dashboard/static/lang/de.js | 17 +++++++++ dashboard/static/lang/en.js | 17 +++++++++ dashboard/static/lang/fr.js | 17 +++++++++ dashboard/static/lang/nl.js | 17 +++++++++ docs/CHANGELOG.md | 6 ++++ postgres/init/054_run_progress.sql | 13 +++++++ tests/test_backup_incremental.py | 8 +++++ 12 files changed, 194 insertions(+), 23 deletions(-) create mode 100644 postgres/init/054_run_progress.sql diff --git a/backup/db.py b/backup/db.py index aedaf48..a9a0454 100644 --- a/backup/db.py +++ b/backup/db.py @@ -190,8 +190,8 @@ def start_run(schedule_id: int, policy_id: Optional[int] = None, occurrence=None def update_run(run_id: int, **fields) -> None: allowed = {'finished_at', 'status', 'task_tag', 'export_path', 'message', 'mode', 'point_kind', 'chain_id', 'point_id', 'proxy_id', 'blocks_changed', 'bytes_written', 'work_started_at', 'lock_wait_seconds', 'copy_seconds', - 'overhead_seconds', 'notice', 'synth_seconds', 'planned_start', 'predicted_finish'} - items = [(k, v) for k, v in fields.items() if k in allowed] + 'overhead_seconds', 'notice', 'synth_seconds', 'planned_start', 'predicted_finish', 'progress'} + items = [(k, _json(v) if k == 'progress' else v) for k, v in fields.items() if k in allowed] if not items: return _exec(f'UPDATE backup.runs SET {", ".join(f"{k} = %s" for k, _ in items)} WHERE id = %s', @@ -809,8 +809,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'} - items = [(k, v) for k, v in fields.items() if k in allowed] + 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] 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]) @@ -1183,13 +1183,13 @@ def queue_test_runs(plan: dict, round_at: datetime, vms: list[dict]) -> int: return n -_TEST_RUN_COLS = ('status', 'verdict', 'agent', 'point_id', 'point_created_at', 'target_cluster_id', 'proxy_id', 'restore_id', +_TEST_RUN_COLS = ('phase', 'progress', 'status', 'verdict', 'agent', 'point_id', 'point_created_at', 'target_cluster_id', 'proxy_id', 'restore_id', 'restored_vm_uuid', 'bytes', 'checks', 'screenshot', 'detail', 'started_at', 'restored_at', 'booted_at', 'finished_at', 'keep_until', 'cleaned_at') def update_test_run(run_id: int, **f) -> None: - items = [(k, _json(v) if k == 'checks' else (psycopg2.Binary(v) if k == 'screenshot' and v is not None else v)) + items = [(k, _json(v) if k in ('checks', 'progress') else (psycopg2.Binary(v) if k == 'screenshot' and v is not None else v)) for k, v in f.items() if k in _TEST_RUN_COLS] if items: _exec(f'UPDATE backup.test_runs SET {", ".join(f"{k} = %s" for k, _ in items)} WHERE id = %s', [v for _, v in items] + [run_id]) @@ -1199,9 +1199,11 @@ def update_test_run(run_id: int, **f) -> None: t.vm_name, t.picked, t.level, t.status, t.verdict, t.agent, t.point_id, t.point_created_at, t.target_cluster_id::text AS target_cluster_id, t.proxy_id, t.restore_id, t.restored_vm_uuid, t.bytes, t.checks, t.detail, t.queued_at, t.started_at, t.restored_at, t.booted_at, t.finished_at, - t.keep_until, t.cleaned_at, (t.screenshot IS NOT NULL) AS has_screenshot, + t.keep_until, t.cleaned_at, (t.screenshot IS NOT NULL) AS has_screenshot, t.phase, t.progress, + rs.progress AS restore_progress, rs.message AS restore_message, c.cluster_name, tc.cluster_name AS target_cluster_name, pl.name AS plan_name FROM backup.test_runs t LEFT JOIN config.clusters c ON c.cluster_id = t.cluster_id + LEFT JOIN backup.restores rs ON rs.id = t.restore_id LEFT JOIN config.clusters tc ON tc.cluster_id = t.target_cluster_id LEFT JOIN backup.test_plans pl ON pl.id = t.plan_id''' diff --git a/backup/incremental.py b/backup/incremental.py index f404f62..8f2b1ef 100644 --- a/backup/incremental.py +++ b/backup/incremental.py @@ -449,7 +449,7 @@ def run_incremental(plan_id: int, policy_id: int | None = None, occurrence=None, db.update_run(run_id, work_started_at=work_started) _run(plan, run_id, hc, work_started, full) except (IncrementalError, HyperCoreError, ProxyError) as e: - db.update_run(run_id, status='ERROR', message=str(e), finished_at=_now()) + db.update_run(run_id, status='ERROR', message=str(e), finished_at=_now(), progress=None) log.error('[run %s] %s', run_id, e) discard_empty_chain(run_id) except Exception as e: # noqa: BLE001 — never kill the scheduler thread @@ -469,6 +469,20 @@ def backup_progress_text(kind: str, p: dict) -> str: return text +def backup_progress(p: dict) -> dict: + """The bar of a running backup: green while copying (MiB of all devices), purple while the proxy checks a + copied disk and reads it back for its checksum (bytes of that disk).""" + total_dev = p.get('devices_total', 1) + out = {'phase': p.get('phase') or 'copy', 'device': min(p.get('devices_done', 0) + 1, total_dev), 'devices': total_dev, + 'done': int(p.get('blocks_done') or 0), 'total': int(p.get('blocks_total') or 0)} + if out['phase'] == 'checksum': + out['done'] = int(p.get('checksum_done') or 0) >> 20 + out['total'] = int(p.get('checksum_total') or 0) >> 20 + elif out['phase'] == 'check': + out['done'], out['total'] = 0, 0 # qemu-img check reports nothing: an indeterminate bar + return out + + def discard_empty_chain(run_id: int) -> bool: """A failed run that had started a new chain (a full) leaves partial files on the share and a chain without points: remove both, or every failed full eats share space until the share is full (live 2026-11-21: two @@ -599,7 +613,7 @@ 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)) + 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'] diff --git a/backup/restore.py b/backup/restore.py index 58091bc..cce2732 100644 --- a/backup/restore.py +++ b/backup/restore.py @@ -93,10 +93,10 @@ 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()) + db.update_restore(restore_id, status='ERROR', message=str(e), 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()) + db.update_restore(restore_id, status='ERROR', message=f'Unexpected error: {e}', finished_at=_now(), progress=None) log.exception('[restore %s] unexpected error', restore_id) @@ -138,15 +138,17 @@ def _run(r: dict) -> None: # verify may be days old; a delta damaged since then would restore silently corrupt. verify = bool(params.get('verify', True)) if verify: - db.update_restore(rid, message='verifying chain') + db.update_restore(rid, message='verifying chain', progress={'phase': 'verify', 'done': 0, 'total': 0}) res_v = incremental.verify_chain(chain, share, pc, upto_seq=point['seq'], - on_progress=lambda p: db.update_restore(rid, message=incremental.verify_progress_text(p))) + on_progress=lambda p: db.update_restore(rid, message=incremental.verify_progress_text(p), + progress={'phase': 'verify', 'done': int(p.get('bytes_done') or 0) >> 20, + 'total': int(p.get('bytes_total') or 0) >> 20})) if not res_v['ok']: detail = '; '.join(f'{d}: {m}' for d, m in res_v['failed'].items()) or 'the proxy reported a mismatch' raise IncrementalError(f'chain integrity check failed, nothing restored: {detail}') # 1. diskless import directory: NVRAM/vTPM with fresh file names + generated XML - db.update_restore(rid, message='preparing definition') + db.update_restore(rid, message='preparing definition', progress={'phase': 'prepare'}) new_uuid = str(uuidlib.uuid4()) utility_files = {u['uuid']: str(uuidlib.uuid4()) for u in utils} xml = render_definition(definition, new_uuid, utility_files) @@ -158,7 +160,7 @@ def _run(r: dict) -> None: 'definition_xml': xml, 'definition_name': f'{dirname}.xml'}), timeout=3600) # 2. import the diskless VM - db.update_restore(rid, message='importing definition') + db.update_restore(rid, message='importing definition', progress={'phase': 'import'}) source_uri = jobs.build_path_uri(f"{share['uri_base'].rstrip('/')}/{out_dir}", share.get('username') or None, share.get('password') or 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 '', @@ -182,12 +184,14 @@ def _run(r: dict) -> None: 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)) - db.update_restore(rid, message=f'writing {len(disks)} disk(s) to the proxy') + 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]}), - on_progress=lambda p: db.update_restore(rid, message=f"writing disks: {p.get('blocks_done', 0)}/{p.get('blocks_total', 0)} MiB"), + on_progress=lambda p: db.update_restore(rid, message=f"writing disks: {p.get('blocks_done', 0)}/{p.get('blocks_total', 0)} MiB", + progress={'phase': 'write', 'done': int(p.get('blocks_done') or 0), + 'total': int(p.get('blocks_total') or 0)}), timeout=8 * 3600)['result'] - db.update_restore(rid, message='attaching disks to the restored VM') + db.update_restore(rid, message='attaching disks to the restored VM', progress={'phase': 'attach'}) snap_uuid = take_snapshot(hc, proxy['vm_uuid'], f'hcm-restore-{rid}', quiesce=False, retain_days=1)['uuid'] for d, su in staging: # the disk goes back on the bus it had (IDE as IDE, SCSI as SCSI): the VM is off, so even @@ -247,7 +251,7 @@ def _run(r: dict) -> None: except ProxyError as e: log.warning('[restore %s] restore directory cleanup failed: %s', rid, e) bytes_written = res.get('bytes_written', 0) - db.update_restore(rid, status='COMPLETE', finished_at=_now(), + db.update_restore(rid, status='COMPLETE', finished_at=_now(), progress=None, message=f"restored as '{name}'" + (f' on {_cluster_name(cid)}' if cid != chain['cluster_id'] else '') + f" ({len(disks)} disk(s), {bytes_written >> 20} MiB written); chain " f"{'verified' if verify else 'not verified (skipped)'}; MAC " diff --git a/backup/testrestore.py b/backup/testrestore.py index b34ef31..bc388b4 100644 --- a/backup/testrestore.py +++ b/backup/testrestore.py @@ -256,6 +256,7 @@ def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, probe_proxy = None if net: probe_proxy = network_ready(hc, target, plan) # raises Fail with what is missing + db.update_test_run(rid, phase='restore') restored = restore(run, plan, target, point, net, state) timeout_s = int(plan['timeout_minutes']) * 60 if net: @@ -264,9 +265,11 @@ def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, t = hc.vm_action(restored, 'START') if t: incremental.wait_task(hc, t, 'start test VM', 600) + db.update_test_run(rid, phase='boot', progress={'started': _now().isoformat(), 'timeout_s': timeout_s}) verdict, detail = watch_boot(hc, target, restored, timeout_s, state, sleep=sleep, clock=clock) db.update_test_run(rid, booted_at=_now()) if net: + db.update_test_run(rid, phase='network', progress={'started': _now().isoformat()}) checks = finish_network_checks(state.pop('netjob'), timeout_s + 600) ok, why = judge_checks(checks) if not ok: @@ -292,9 +295,11 @@ def run_test(run: dict, plan: dict, target: str, point: dict, sleep=time.sleep, if status == 'failed' and plan.get('keep_failed_hours') and state['restored']: keep = _now() + timedelta(hours=int(plan['keep_failed_hours'])) db.update_test_run(rid, status=status, verdict=verdict, detail=detail, checks=checks, finished_at=_now(), - screenshot=state['png'], keep_until=keep) + screenshot=state['png'], keep_until=keep, phase='cleanup' if state['restored'] and not keep else None, + progress=None) if state['restored'] and not keep: cleanup(target, state['restored'], rid) + db.update_test_run(rid, phase=None) _alerts(run, plan, status, verdict, detail) with _guard: _running.pop(target, None) diff --git a/dashboard/static/index.html b/dashboard/static/index.html index d616084..4dfdc04 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -712,6 +712,15 @@ .ex-slots { display: inline-flex; gap: 2px; vertical-align: middle; margin-right: 6px; } .ex-slots i { width: 6px; height: 14px; border-radius: 2px; background: var(--accent-cyan); display: block; opacity: 0.85; } .ex-badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 10px; font-family: 'JetBrains Mono', monospace; } + /* progress of running work: green while copying or writing, purple while verifying (like balenaEtcher) */ + .hcm-pbar { position: relative; height: 8px; min-width: 180px; max-width: 360px; border-radius: 4px; background: var(--bg-nested, rgba(127,127,127,0.15)); overflow: hidden; margin-top: 4px; } + .hcm-pbar-fill { height: 100%; border-radius: 4px; transition: width .6s ease; background: var(--accent-green); } + .hcm-pbar.verify .hcm-pbar-fill { background: var(--accent-purple); } + .hcm-pbar.indet .hcm-pbar-fill { width: 35% !important; position: absolute; animation: hcm-pbar-slide 1.4s ease-in-out infinite; } + @keyframes hcm-pbar-slide { 0% { left: -35%; } 100% { left: 100%; } } + .hcm-pbar-label { font-size: 10px; font-family: 'JetBrains Mono', monospace; color: var(--text-muted); margin-top: 3px; } + .hcm-pbar-label b { color: var(--text-secondary); font-weight: 600; } + @media (prefers-reduced-motion: reduce) { .hcm-pbar.indet .hcm-pbar-fill { animation: none; left: 0; width: 100% !important; opacity: .5; } } .ex-badge.ok { background: rgba(16,185,129,0.15); color: var(--accent-green); } .ex-badge.err { background: rgba(239,68,68,0.15); color: var(--accent-red); } .ex-badge.run { background: rgba(6,182,212,0.15); color: var(--accent-cyan); } @@ -6920,7 +6929,9 @@

HyperCore Manager

${_exEsc(kind === 'imp' ? r.source_uri : r.vm_name)}${(kind === 'imp' || kind === 'rst') && r.target_name ? ` → ${_exEsc(r.target_name)}` : ''}${_exClusterHint(r)}${kind === 'run' && r.export_path ? `
${_exEsc(r.export_path)}
` : ''}
${_exFmt(r.started_at)}${_exStatusBadge(r.status, r.message)}${kind === 'run' && r.notice ? ' ' + _exNoticeBadge(r.notice) : ''}${r.status === 'RUNNING' && kind === 'run' && r.progress ? _pbBackup(r.progress) + : r.status === 'RUNNING' && kind === 'rst' && r.progress ? _pbRestore(r.progress) + : _exStatusBadge(r.status, r.message)}${kind === 'run' && r.notice ? ' ' + _exNoticeBadge(r.notice) : ''} ${kind === 'run' && r.mode ? `${r.mode === 'incremental' ? t(r.point_kind === 'full' ? 'ex.point_full' : 'ex.point_delta') : t('ex.mode_export')} ` : ''}${kind === 'rst' && r.kind === 'files' ? `${t('ex.files')} ` : ''}${r.status === 'RUNNING' ? '' : _exEsc(r.message || '')}${kind === 'rst' && r.kind === 'files' && r.created_uuid && r.status === 'COMPLETE' ? ` ` : ''}${r.task_tag ? `
task ${_exEsc(r.task_tag)}
` : ''}
` : `
${t('ex.no_runs')}
`}
`; @@ -6928,7 +6939,7 @@

HyperCore Manager

if (!_exRunsFilter) { try { tests = await _exCall('GET', '/api/backup/test-runs?limit=100'); } catch (e) { tests = []; } } el.innerHTML = table(t('ex.runs_title'), runs, 'run') + (_exRunsFilter ? '' : _trHistory(tests) + table(t('ex.restores_title'), restores, 'rst') + table(t('ex.imports_title'), imports, 'imp') + _vfHistory(d.verifications || [])); clearTimeout(_exPollTimer); - if ([...runs, ...imports, ...restores].some(r => r.status === 'RUNNING')) { + if ([...runs, ...imports, ...restores].some(r => r.status === 'RUNNING') || tests.some(r => r.status === 'running' || r.status === 'queued')) { // poll while anything runs, but only while this panel is on screen and the cluster unchanged const cid = currentCluster; _exPollTimer = setTimeout(() => { if (currentCluster === cid && document.getElementById('expanel-runs')?.classList.contains('active')) exLoadRuns(); }, 5000); @@ -7013,6 +7024,46 @@

HyperCore Manager

: `
${t('vf.history_none')}
`}`; } +// ── progress bars of running work ────────────────────────────────────────────────────────────────── +const _pbGiB = mib => (mib / 1024).toFixed(1); +/** A bar plus a label. pr: {phase, done, total} (MiB); green for copy/write, purple for verify/check/checksum, + * sliding (indeterminate) when the total is unknown. */ +function _pbar(pr, label) { + const verify = ['verify', 'check', 'checksum', 'boot', 'network'].includes(pr.phase); + const pct = pr.total ? Math.max(0, Math.min(100, Math.round(pr.done * 100 / pr.total))) : null; + return `
+
+
${label}${pct === null ? '' : ` · ${pct}%`}
`; +} +function _pbAmount(pr) { return pr.total ? `${_pbGiB(pr.done)} / ${_pbGiB(pr.total)} GiB` : ''; } +/** A running backup: copying (green), then per disk checking and checksum read-back (purple). */ +function _pbBackup(pr) { + if (!pr || !pr.phase) return ''; + const disk = pr.devices > 1 ? ` · ${t('pb.disk_of', {n: pr.device, total: pr.devices})}` : ''; + if (pr.phase === 'check') return _pbar(pr, `${t('pb.check')}${disk}`); + if (pr.phase === 'checksum') return _pbar(pr, `${t('pb.checksum')} ${_pbAmount(pr)}${disk}`); + return _pbar(pr, `${t('pb.copy')} ${_pbAmount(pr)}${disk}`); +} +/** A running restore: verifying the chain (purple), preparing and importing (green, sliding), writing disks (green). */ +function _pbRestore(pr) { + if (!pr || !pr.phase) return ''; + const key = {verify: 'pb.verify_chain', prepare: 'pb.prepare', import: 'pb.import', write: 'pb.write', attach: 'pb.attach'}[pr.phase] || 'pb.working'; + return _pbar(pr, `${t(key)} ${_pbAmount(pr)}`); +} +const _pbClock = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`; +/** A running test restore: restore (the restore's own bar), boot (elapsed against the timeout), network checks, clean-up. */ +function _pbTest(r) { + const step = n => `${t('pb.step', {n, total: r.level === 'network' ? 3 : 2})}`; + if (r.phase === 'restore') return step(1) + (_pbRestore(r.restore_progress) || _pbar({phase: 'prepare'}, `${t('pb.restore')}`)); + if (r.phase === 'boot' && r.progress) { + const el = Math.max(0, (Date.now() - new Date(r.progress.started).getTime()) / 1000), to = r.progress.timeout_s || 600; + return step(2) + _pbar({phase: 'boot', done: Math.min(el, to), total: to}, `${t('pb.boot')} ${_pbClock(el)} / ${_pbClock(to)}`); + } + if (r.phase === 'network') return step(3) + _pbar({phase: 'network'}, `${t('pb.network')}`); + if (r.phase === 'cleanup') return _pbar({phase: 'prepare'}, `${t('pb.cleanup')}`); + return ''; +} + // ── test restores (per folder): plans on the Schedules tab, results on the Runs tab, a column on the // restore points ───────────────────────────────────────────────────────────────────────────────────── let _trData = null, _trEditing = null; // _trEditing: null | 'new' | plan id @@ -7150,7 +7201,7 @@

HyperCore Manager

${rows.map(r => ` ${_exEsc(r.vm_name || '?')}${_exClusterHint(r)}
${_exEsc(r.plan_name || '')}${r.picked === 'random' ? ' · ' + t('tr.picked_random') : ''}
${_exFmt(r.started_at || r.queued_at)} - ${_trStatusBadge(r)}${r.verdict === 'agent' ? ` ${t('tr.v_agent')}` : r.verdict === 'screen' ? ` ${t('tr.v_screen')}` : ''} + ${_trStatusBadge(r)}${r.status === 'running' ? _pbTest(r) : ''}${r.verdict === 'agent' ? ` ${t('tr.v_agent')}` : r.verdict === 'screen' ? ` ${t('tr.v_screen')}` : ''} ${r.agent === 'unavailable' ? `
${t('tr.agentless')}
` : r.agent === 'unknown' ? `
${t('tr.agent_unknown')}
` : ''} ${r.target_cluster_name ? t('tr.on_cluster', {cluster: _exEsc(r.target_cluster_name)}) : ''}${r.point_created_at ? ` · ${t('tr.point_age', {h: ago(r.point_created_at)})}` : ''}${r.bytes ? ` · ${_exMiB(Math.round(r.bytes / 1048576))}` : ''}${r.restored_at ? ` · ${t('tr.restore_took', {d: dur(r.started_at, r.restored_at)})}` : ''}${r.booted_at ? ` · ${t('tr.boot_took', {d: dur(r.restored_at, r.booted_at)})}` : ''} diff --git a/dashboard/static/lang/de.js b/dashboard/static/lang/de.js index 5f74b00..08b3de8 100644 --- a/dashboard/static/lang/de.js +++ b/dashboard/static/lang/de.js @@ -1796,4 +1796,21 @@ window.LANG = { 'tr.chain_failed': "fehlgeschlagen {when}", 'notice.test_failed': "Test-Wiederherstellung von {vm} fehlgeschlagen: {detail}. Das Backup ist für eine echte Wiederherstellung möglicherweise nicht brauchbar.", 'notice.test_overdue': "{vm} wird nicht testweise wiederhergestellt: {detail}.", + + // progress bars of running work + 'pb.copy': "Kopieren", + 'pb.check': "Prüfen: Image wird geprüft", + 'pb.checksum': "Prüfen: Prüfsumme", + 'pb.disk_of': "Disk {n} von {total}", + 'pb.verify_chain': "Kette prüfen", + 'pb.prepare': "VM-Definition vorbereiten", + 'pb.import': "VM importieren", + 'pb.write': "Disks schreiben", + 'pb.attach': "Disks anhängen", + 'pb.working': "In Arbeit", + 'pb.restore': "Wiederherstellen", + 'pb.boot': "Start: warten auf ein Lebenszeichen", + 'pb.network': "Netzwerkprüfungen im Test-VLAN", + 'pb.cleanup': "Test-VM wird entfernt", + 'pb.step': "Schritt {n}/{total}", }; diff --git a/dashboard/static/lang/en.js b/dashboard/static/lang/en.js index fd4fa2d..7fd5a7f 100644 --- a/dashboard/static/lang/en.js +++ b/dashboard/static/lang/en.js @@ -1797,4 +1797,21 @@ window.LANG = { 'tr.chain_failed': "failed {when}", 'notice.test_failed': "Test restore of {vm} failed: {detail}. The backup may not be usable for a real restore.", 'notice.test_overdue': "{vm} is not being test-restored: {detail}.", + + // progress bars of running work + 'pb.copy': "Copying", + 'pb.check': "Verifying: checking the image", + 'pb.checksum': "Verifying: checksum", + 'pb.disk_of': "disk {n} of {total}", + 'pb.verify_chain': "Verifying the chain", + 'pb.prepare': "Preparing the VM definition", + 'pb.import': "Importing the VM", + 'pb.write': "Writing disks", + 'pb.attach': "Attaching disks", + 'pb.working': "Working", + 'pb.restore': "Restoring", + 'pb.boot': "Booting: waiting for a sign of life", + 'pb.network': "Network checks on the test VLAN", + 'pb.cleanup': "Removing the test VM", + 'pb.step': "step {n}/{total}", }; diff --git a/dashboard/static/lang/fr.js b/dashboard/static/lang/fr.js index e7a8b32..7ca692e 100644 --- a/dashboard/static/lang/fr.js +++ b/dashboard/static/lang/fr.js @@ -1796,4 +1796,21 @@ window.LANG = { 'tr.chain_failed': "échoué {when}", 'notice.test_failed': "Restauration de test de {vm} échouée : {detail}. La sauvegarde n'est peut-être pas utilisable pour une vraie restauration.", 'notice.test_overdue': "{vm} n'est pas testée par restauration : {detail}.", + + // progress bars of running work + 'pb.copy': "Copie", + 'pb.check': "Vérification : contrôle de l'image", + 'pb.checksum': "Vérification : somme de contrôle", + 'pb.disk_of': "disque {n} sur {total}", + 'pb.verify_chain': "Vérification de la chaîne", + 'pb.prepare': "Préparation de la définition de la VM", + 'pb.import': "Import de la VM", + 'pb.write': "Écriture des disques", + 'pb.attach': "Attachement des disques", + 'pb.working': "En cours", + 'pb.restore': "Restauration", + 'pb.boot': "Démarrage : attente d'un signe de vie", + 'pb.network': "Contrôles réseau sur le VLAN de test", + 'pb.cleanup': "Suppression de la VM de test", + 'pb.step': "étape {n}/{total}", }; diff --git a/dashboard/static/lang/nl.js b/dashboard/static/lang/nl.js index db23a0a..0ba609d 100644 --- a/dashboard/static/lang/nl.js +++ b/dashboard/static/lang/nl.js @@ -1796,4 +1796,21 @@ window.LANG = { 'tr.chain_failed': "mislukt {when}", 'notice.test_failed': "Testherstel van {vm} mislukt: {detail}. De back-up is mogelijk niet bruikbaar voor een echt herstel.", 'notice.test_overdue': "{vm} wordt niet testhersteld: {detail}.", + + // progress bars of running work + 'pb.copy': "Kopiëren", + 'pb.check': "Controleren: image nakijken", + 'pb.checksum': "Controleren: controlesom", + 'pb.disk_of': "schijf {n} van {total}", + 'pb.verify_chain': "Keten controleren", + 'pb.prepare': "VM-definitie voorbereiden", + 'pb.import': "VM importeren", + 'pb.write': "Schijven schrijven", + 'pb.attach': "Schijven koppelen", + 'pb.working': "Bezig", + 'pb.restore': "Herstellen", + 'pb.boot': "Opstarten: wachten op een teken van leven", + 'pb.network': "Netwerkcontroles op het test-VLAN", + 'pb.cleanup': "Test-VM verwijderen", + 'pb.step': "stap {n}/{total}", }; diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a4d1683..4210633 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -57,6 +57,12 @@ All notable changes to this project are documented here. The format follows badge on the cluster card, and mailed to the closest administrator of the folder (the folder's admins, else the customer's, else the MSP's, else the installation's). A chain with a point not verified for twice the interval raises a warning badge and a mail of its own. One mail per folder gathers what failed within two minutes. +- **Progress bars for running work** (like balenaEtcher): a running backup shows a green bar while copying + (GiB and disk n of m), then a purple one while the proxy checks the image and reads it back for its checksum; a + running restore shows verifying (purple), preparing and importing, writing disks (green); a running test + restore shows its step: restoring (the restore's bar), booting (time waited against the timeout), network checks, + removing the test VM. Migration 054 stores the structured progress next to the text. + - Restore points show a **Verified** column per chain; Runs lists the verifications (proxy, size, duration). ### Changed diff --git a/postgres/init/054_run_progress.sql b/postgres/init/054_run_progress.sql new file mode 100644 index 0000000..bb168e1 --- /dev/null +++ b/postgres/init/054_run_progress.sql @@ -0,0 +1,13 @@ +-- ============================================================================= +-- 054_run_progress.sql +-- Structured progress for running work, so the dashboard can draw a bar instead of only a text line +-- (William 2026-11-21: "like balenaEtcher, green while copying, purple while verifying"). +-- runs: {phase: copy | check | checksum, done, total (MiB), device, devices} +-- restores: {phase: verify | prepare | import | write | attach | finish, done, total (MiB)} +-- test_runs: phase (queued -> restore -> boot -> network -> cleanup) and progress {started, timeout_s} +-- Idempotent. +-- ============================================================================= +ALTER TABLE backup.runs ADD COLUMN IF NOT EXISTS progress JSONB; +ALTER TABLE backup.restores ADD COLUMN IF NOT EXISTS progress JSONB; +ALTER TABLE backup.test_runs ADD COLUMN IF NOT EXISTS phase TEXT; +ALTER TABLE backup.test_runs ADD COLUMN IF NOT EXISTS progress JSONB; diff --git a/tests/test_backup_incremental.py b/tests/test_backup_incremental.py index cf97c01..63f4244 100644 --- a/tests/test_backup_incremental.py +++ b/tests/test_backup_incremental.py @@ -797,3 +797,11 @@ def test_backup_progress_says_what_happens_after_the_copy(): assert inc.backup_progress_text('full', dict(p, phase='check')).endswith(': checking the image') assert inc.backup_progress_text('full', dict(p, phase='checksum', checksum_done=12 << 30, checksum_total=27 << 30)).endswith( ': checksum 12288/27648 MiB') + + +def test_backup_progress_feeds_the_two_colour_bar(): + p = {'blocks_done': 1200, 'blocks_total': 28141, 'devices_done': 0, 'devices_total': 3} + assert inc.backup_progress(p) == {'phase': 'copy', 'device': 1, 'devices': 3, 'done': 1200, 'total': 28141} + assert inc.backup_progress(dict(p, phase='check'))['total'] == 0, 'qemu-img check: no amount, a sliding bar' + c = inc.backup_progress(dict(p, phase='checksum', checksum_done=5 << 30, checksum_total=27 << 30)) + assert (c['phase'], c['done'], c['total']) == ('checksum', 5120, 27648) From fd856dc2bc957e0b59a10734ad4f2aa14d8372e7 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 00:28:23 +0100 Subject: [PATCH 5/7] fix(ui): the Runs tab picks up runs that start while it is open (polls every 20 s when idle) --- dashboard/static/index.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 4dfdc04..5bce89f 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -6939,11 +6939,11 @@

HyperCore Manager

if (!_exRunsFilter) { try { tests = await _exCall('GET', '/api/backup/test-runs?limit=100'); } catch (e) { tests = []; } } el.innerHTML = table(t('ex.runs_title'), runs, 'run') + (_exRunsFilter ? '' : _trHistory(tests) + table(t('ex.restores_title'), restores, 'rst') + table(t('ex.imports_title'), imports, 'imp') + _vfHistory(d.verifications || [])); clearTimeout(_exPollTimer); - if ([...runs, ...imports, ...restores].some(r => r.status === 'RUNNING') || tests.some(r => r.status === 'running' || r.status === 'queued')) { - // poll while anything runs, but only while this panel is on screen and the cluster unchanged - const cid = currentCluster; - _exPollTimer = setTimeout(() => { if (currentCluster === cid && document.getElementById('expanel-runs')?.classList.contains('active')) exLoadRuns(); }, 5000); - } + // poll every 5 s while anything runs, every 20 s otherwise (a run started by a schedule or another user shows up + // with its progress bar), but only while this panel is on screen and the cluster unchanged + const busy = [...runs, ...imports, ...restores].some(r => r.status === 'RUNNING') || tests.some(r => r.status === 'running' || r.status === 'queued'); + const cid = currentCluster; + _exPollTimer = setTimeout(() => { if (currentCluster === cid && document.getElementById('expanel-runs')?.classList.contains('active')) exLoadRuns(); }, busy ? 5000 : 20000); } // ── planned verification (per folder): settings and state on the Schedules tab, a column on the restore From 52472f4d25b75ca22747488e6b55ba23067d53f8 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 09:41:40 +0100 Subject: [PATCH 6/7] fix(ui): the backup bar counts devices, not disks (NVRAM and vTPM are devices too) --- dashboard/static/index.html | 8 ++++---- dashboard/static/lang/de.js | 2 +- dashboard/static/lang/en.js | 2 +- dashboard/static/lang/fr.js | 2 +- dashboard/static/lang/nl.js | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 5bce89f..d7c71d7 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -7039,10 +7039,10 @@

HyperCore Manager

/** A running backup: copying (green), then per disk checking and checksum read-back (purple). */ function _pbBackup(pr) { if (!pr || !pr.phase) return ''; - const disk = pr.devices > 1 ? ` · ${t('pb.disk_of', {n: pr.device, total: pr.devices})}` : ''; - if (pr.phase === 'check') return _pbar(pr, `${t('pb.check')}${disk}`); - if (pr.phase === 'checksum') return _pbar(pr, `${t('pb.checksum')} ${_pbAmount(pr)}${disk}`); - return _pbar(pr, `${t('pb.copy')} ${_pbAmount(pr)}${disk}`); + const dev = pr.devices > 1 ? ` · ${t('pb.device_of', {n: pr.device, total: pr.devices})}` : ''; + if (pr.phase === 'check') return _pbar(pr, `${t('pb.check')}${dev}`); + if (pr.phase === 'checksum') return _pbar(pr, `${t('pb.checksum')} ${_pbAmount(pr)}${dev}`); + return _pbar(pr, `${t('pb.copy')} ${_pbAmount(pr)}${dev}`); } /** A running restore: verifying the chain (purple), preparing and importing (green, sliding), writing disks (green). */ function _pbRestore(pr) { diff --git a/dashboard/static/lang/de.js b/dashboard/static/lang/de.js index 08b3de8..724f54d 100644 --- a/dashboard/static/lang/de.js +++ b/dashboard/static/lang/de.js @@ -1801,7 +1801,7 @@ window.LANG = { 'pb.copy': "Kopieren", 'pb.check': "Prüfen: Image wird geprüft", 'pb.checksum': "Prüfen: Prüfsumme", - 'pb.disk_of': "Disk {n} von {total}", + 'pb.device_of': "Gerät {n} von {total}", 'pb.verify_chain': "Kette prüfen", 'pb.prepare': "VM-Definition vorbereiten", 'pb.import': "VM importieren", diff --git a/dashboard/static/lang/en.js b/dashboard/static/lang/en.js index 7fd5a7f..21733c5 100644 --- a/dashboard/static/lang/en.js +++ b/dashboard/static/lang/en.js @@ -1802,7 +1802,7 @@ window.LANG = { 'pb.copy': "Copying", 'pb.check': "Verifying: checking the image", 'pb.checksum': "Verifying: checksum", - 'pb.disk_of': "disk {n} of {total}", + 'pb.device_of': "device {n} of {total}", 'pb.verify_chain': "Verifying the chain", 'pb.prepare': "Preparing the VM definition", 'pb.import': "Importing the VM", diff --git a/dashboard/static/lang/fr.js b/dashboard/static/lang/fr.js index 7ca692e..f2d388b 100644 --- a/dashboard/static/lang/fr.js +++ b/dashboard/static/lang/fr.js @@ -1801,7 +1801,7 @@ window.LANG = { 'pb.copy': "Copie", 'pb.check': "Vérification : contrôle de l'image", 'pb.checksum': "Vérification : somme de contrôle", - 'pb.disk_of': "disque {n} sur {total}", + 'pb.device_of': "périphérique {n} sur {total}", 'pb.verify_chain': "Vérification de la chaîne", 'pb.prepare': "Préparation de la définition de la VM", 'pb.import': "Import de la VM", diff --git a/dashboard/static/lang/nl.js b/dashboard/static/lang/nl.js index 0ba609d..aae807a 100644 --- a/dashboard/static/lang/nl.js +++ b/dashboard/static/lang/nl.js @@ -1801,7 +1801,7 @@ window.LANG = { 'pb.copy': "Kopiëren", 'pb.check': "Controleren: image nakijken", 'pb.checksum': "Controleren: controlesom", - 'pb.disk_of': "schijf {n} van {total}", + 'pb.device_of': "apparaat {n} van {total}", 'pb.verify_chain': "Keten controleren", 'pb.prepare': "VM-definitie voorbereiden", 'pb.import': "VM importeren", From 5b19eab53b3de20b9a14e6ebde88d5412af9db08 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 09:41:40 +0100 Subject: [PATCH 7/7] chore: release 1.7.0 --- VERSION | 2 +- docs/CHANGELOG.md | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/VERSION b/VERSION index dc1e644..bd8bf88 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.6.0 +1.7.0 diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4210633..faffccb 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). -## [Unreleased] +## [1.7.0] ### Added - **Test restores.** A test plan per folder (Backup → Schedules → **Test restores**) restores the newest backup of @@ -29,6 +29,12 @@ All notable changes to this project are documented here. The format follows - **Proxy deploy: Test VLAN** adds a second NIC for the network checks. Proxy **0.6.2**: job `netcheck`, `iproute2`, `iputils-ping` and `dnsmasq-base` in the image; proxies deployed from now on run with host networking (older ones show *network tests: redeploy*). +- **Progress bars for running work** (like balenaEtcher): a running backup shows a green bar while copying + (GiB and device n of m), then a purple one while the proxy checks the image and reads it back for its checksum; a + running restore shows verifying (purple), preparing and importing, writing disks (green); a running test + restore shows its step: restoring (the restore's bar), booting (time waited against the timeout), network checks, + removing the test VM. The Runs tab now also refreshes every 20 s when nothing runs, so runs started by a + schedule or another user show up with their bar. Migration 054 stores the structured progress next to the text. ### Fixed - **A big full looked stuck at its last MiB.** After a disk is copied the proxy checks the image and reads it back @@ -38,6 +44,11 @@ All notable changes to this project are documented here. The format follows interrupted runs runs shortly after every (re)start of the backup service and also deleted the clones of a run that had just begun (`No such file or directory: /dev/disk/by-id/virtio-…`). It now skips chains whose backup is running. +- **A failed full no longer leaves its partial data on the share.** A full that failed before its first point + kept what it had copied, so repeated failures filled the share. An empty chain of a failed run is now removed. +- **A Windows lock screen showing only the clock is recognised** by the console's screen check (a second OCR pass + for white text on a photo), so a booted BitLocker VM without a guest agent counts as up. +- The proxy list says *guest agent unknown (source VM is off)* instead of *agent unknown*. ## [1.6.0] @@ -57,12 +68,6 @@ All notable changes to this project are documented here. The format follows badge on the cluster card, and mailed to the closest administrator of the folder (the folder's admins, else the customer's, else the MSP's, else the installation's). A chain with a point not verified for twice the interval raises a warning badge and a mail of its own. One mail per folder gathers what failed within two minutes. -- **Progress bars for running work** (like balenaEtcher): a running backup shows a green bar while copying - (GiB and disk n of m), then a purple one while the proxy checks the image and reads it back for its checksum; a - running restore shows verifying (purple), preparing and importing, writing disks (green); a running test - restore shows its step: restoring (the restore's bar), booting (time waited against the timeout), network checks, - removing the test VM. Migration 054 stores the structured progress next to the text. - - Restore points show a **Verified** column per chain; Runs lists the verifications (proxy, size, duration). ### Changed