Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.7.3
1.7.4
10 changes: 4 additions & 6 deletions backup/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,10 @@ def status():
loc = jobs.location_for_cluster(cid) if cid else None
pf = None
if cid:
try:
pf = jobs.preflight(jobs.client_for(cid), cid, max_age=60)
if not pf['ok']:
pf = dict(pf, hint=jobs.DEFERRED_HINT.get(pf['kind'], ''))
except HyperCoreError as e:
pf = {'ok': True, 'kind': None, 'detail': '', 'nodes': [], 'unavailable': str(e)}
# never wait for the cluster here: the last answer, refreshed in the background when stale
pf = jobs.preflight_cached(cid, max_age=60)
if pf and not pf['ok']:
pf = dict(pf, hint=jobs.DEFERRED_HINT.get(pf['kind'], ''))
return jsonify({
'service': 'backup',
# update in progress / node missing: the dashboard shows a banner, runs are deferred
Expand Down
32 changes: 32 additions & 0 deletions backup/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import logging
import re
import shutil
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
Expand Down Expand Up @@ -211,6 +212,37 @@ def preflight(hc: HyperCoreClient, cluster_id: str | None = None, max_age: float
return result


_PREFLIGHT_REFRESHING: set[str] = set()
_PREFLIGHT_LOCK = threading.Lock()


def preflight_cached(cluster_id: str, max_age: float = 60, client_factory=None) -> dict | None:
"""The last known pre-flight answer for the dashboard, without waiting for the cluster. A missing or
stale answer is refreshed in a background thread (one per cluster at a time); until the first answer
arrives this returns None. Asking the cluster live made /status take as long as the HyperCore login,
which with a node down (timeouts per node) outlasted the dashboard's 3 s and hid the Backup tab."""
hit = _PREFLIGHT_CACHE.get(cluster_id)
if hit and time.monotonic() - hit[0] < max_age:
return hit[1]
with _PREFLIGHT_LOCK:
if cluster_id in _PREFLIGHT_REFRESHING:
return hit[1] if hit else None
_PREFLIGHT_REFRESHING.add(cluster_id)

def refresh():
try:
preflight((client_factory or client_for)(cluster_id), cluster_id)
except Exception as e: # noqa: BLE001 -- unreachable cluster: the next call tries again
log.info('[%s] pre-flight for the dashboard failed: %s', cluster_id, e)
_PREFLIGHT_CACHE[cluster_id] = (time.monotonic(), {'ok': True, 'kind': None, 'detail': '', 'nodes': [],
'unavailable': str(e)})
finally:
with _PREFLIGHT_LOCK:
_PREFLIGHT_REFRESHING.discard(cluster_id)
threading.Thread(target=refresh, name=f'preflight-{cluster_id[:8]}', daemon=True).start()
return hit[1] if hit else None


def wait_until_clear(hc: HyperCoreClient, on_wait, max_hours: float | None = None, poll_seconds: int | None = None) -> dict:
"""Pre-flight, repeated until the cluster is idle or the wait is used up. on_wait(detail) is
called whenever the reason changes. Returns the last pre-flight result (ok or not)."""
Expand Down
14 changes: 12 additions & 2 deletions dashboard/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2023,14 +2023,24 @@ def backup_status():
try:
rq = urllib.request.Request(f'{url}/api/v1/status?cluster={_cluster_id()}',
headers={'Authorization': f'Bearer {token}'} if token else {})
with urllib.request.urlopen(rq, timeout=3) as resp:
with urllib.request.urlopen(rq, timeout=5) as resp:
data = json.loads(resp.read().decode())
data['available'] = True
return jsonify(data if _access().can('backup.targets.manage') else _strip_sensitive(data))
except Exception:
except Exception as e: # noqa: BLE001
# a slow answer is not a missing service: keep the tab (it hid while a node was down); only a
# refused or unresolvable connection means the backup container is not running
if _is_timeout(e):
return jsonify({'available': True, 'status_slow': True})
return jsonify({'available': False})


def _is_timeout(e: BaseException) -> bool:
import socket
reason = getattr(e, 'reason', e)
return isinstance(reason, (socket.timeout, TimeoutError)) or 'timed out' in str(reason).lower()


@app.route('/api/backup/<path:sub>', methods=['GET', 'POST', 'PUT', 'DELETE'])
@requires(None)
def backup_proxy(sub):
Expand Down
7 changes: 4 additions & 3 deletions dashboard/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6177,11 +6177,12 @@ <h1>HyperCore <span>Manager</span></h1>
return false;
}
const d = await apiFetch('/api/backup/status');
_exAvailable = !!(d && d.available);
if (d && d.available) { _exDefaults = d; _exLocation = d.location || null; _exClusterZone = d.cluster_timezone || ''; }
const tab = document.getElementById('navTabExports');
if (!d) return _exAvailable; // the request itself failed (network, dashboard restart): leave the tab as it is
_exAvailable = !!d.available;
if (d.available && !d.status_slow) { _exDefaults = d; _exLocation = d.location || null; _exClusterZone = d.cluster_timezone || ''; }
if (tab) tab.hidden = !_exAvailable;
_exPreflightBanner(d && d.available ? d.preflight : null);
if (!d.status_slow) _exPreflightBanner(d.available ? d.preflight : null);
return _exAvailable;
}
// cluster self-update or a node missing: HyperCore cannot snapshot, so every backup, export and
Expand Down
10 changes: 10 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ 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/).

## [1.7.4]

### Fixed
- **The Backup tab no longer disappears while a cluster answers slowly.** The backup service's status asked the
cluster live (update state and nodes) and so took as long as the HyperCore login: with a node down, or a newly
registered cluster whose nodes did not answer, that outlasted the dashboard's 3 s and the tab was hidden, for
everyone, just when a node was missing. The status now answers from the last known pre-flight and refreshes it in
the background (one refresh per cluster at a time); a status that times out keeps the tab (only a refused
connection, a stopped backup service, hides it); and a failed status request leaves the tab as it was.

## [1.7.3]

### Fixed
Expand Down
33 changes: 33 additions & 0 deletions tests/test_backup_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import importlib
import os
import sys
import time

import pytest

Expand Down Expand Up @@ -217,3 +218,35 @@ def test_nfs_is_refused_for_hypercore_import_and_export(monkeypatch):
monkeypatch.setattr(jobs.db, 'update_import', lambda iid, **f: imports.update(f))
jobs.run_import(3)
assert imports['status'] == 'ERROR' and 'SMB only' in imports['message'] and not asked


def test_preflight_for_the_dashboard_never_waits_for_the_cluster(monkeypatch):
"""/status answers from the last pre-flight; a stale or missing one is refreshed in the background, once per
cluster at a time, so a slow login (a node down) cannot make the dashboard hide the Backup tab."""
import threading
jobs._PREFLIGHT_CACHE.clear(); jobs._PREFLIGHT_REFRESHING.clear()
gate, calls = threading.Event(), []

class SlowHC:
def update_status(self): return {}
def list_nodes(self):
calls.append(1); gate.wait(5)
return [{'lanIP': '10.0.0.1', 'networkStatus': 'ONLINE'}]
assert jobs.preflight_cached('c1', client_factory=lambda cid: SlowHC()) is None, 'first call: nothing known yet, no wait'
assert jobs.preflight_cached('c1', client_factory=lambda cid: SlowHC()) is None
gate.set()
for _ in range(50):
if 'c1' in jobs._PREFLIGHT_CACHE and not jobs._PREFLIGHT_REFRESHING: break
time.sleep(0.02)
assert len(calls) == 1, 'one refresh at a time per cluster'
assert jobs.preflight_cached('c1', client_factory=lambda cid: SlowHC())['ok'] is True
# stale: the old answer comes back at once while a refresh runs; a failing cluster leaves a non-blocking answer
jobs._PREFLIGHT_CACHE['c1'] = (time.monotonic() - 120, {'ok': False, 'kind': 'node', 'detail': 'old', 'nodes': []})

def boom(cid): raise jobs.HyperCoreError('login timed out')
assert jobs.preflight_cached('c1', client_factory=boom)['detail'] == 'old'
for _ in range(50):
if not jobs._PREFLIGHT_REFRESHING: break
time.sleep(0.02)
pf = jobs.preflight_cached('c1', client_factory=boom)
assert pf['ok'] is True and 'timed out' in pf['unavailable']
Loading