Add graceful Director unavailable UI and diagnostic script

- Director API returns 503 with helpful error details when BGD is down
- New unavailable banner in director.html with troubleshooting hints
- Created scripts/diagnostic.py for full connectivity testing
- Launcher diagnostics now runs server-side checks via diagnostic.py
- All Director endpoints handle connection errors gracefully
This commit is contained in:
Reditus committed 2026-05-15 15:53:08 +01:00
1 parent 6efce4dbcb
commit bbdc0ab39c
5 files changed
+360 -13

No files matched your search

+25 -7
View File
@@ -922,20 +922,28 @@ def register_api_routes(app, services, settings):
def director_battlegroup(): def director_battlegroup():
try: try:
if not director_svc: if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 500 return jsonify({'success': False, 'error': 'Director service not available'}), 503
logger.info("Director request: %s/v0/battlegroup", director_svc.base_url) logger.info("Director request: %s/v0/battlegroup", director_svc.base_url)
data = director_svc.get_battlegroup() data = director_svc.get_battlegroup()
return data, 200, {'Content-Type': 'application/json'} return data, 200, {'Content-Type': 'application/json'}
except Exception as e: except Exception as e:
error_msg = str(e)
logger.error("Director battlegroup error: %s", e) logger.error("Director battlegroup error: %s", e)
return jsonify({'success': False, 'error': str(e)}), 500 if 'refused' in error_msg.lower() or 'closed' in error_msg.lower() or 'aborted' in error_msg.lower():
return jsonify({
'success': False,
'error': 'Director unavailable',
'detail': 'The Battlegroup Director service is not responding. This usually means the BGD pod is starting up or has crashed due to RabbitMQ/database connectivity issues.',
'hint': 'Check the BGD pod logs on the server: sudo kubectl logs -n <namespace> -l app=<namespace>-bgd-deploy --tail=50'
}), 503
return jsonify({'success': False, 'error': error_msg}), 500
@app.route('/api/director/update_config', methods=['POST']) @app.route('/api/director/update_config', methods=['POST'])
@auth_req @auth_req
def director_update_config(): def director_update_config():
try: try:
if not director_svc: if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 500 return jsonify({'success': False, 'error': 'Director service not available'}), 503
config = request.get_json() config = request.get_json()
map_name = config.get('MapName', '') map_name = config.get('MapName', '')
result = director_svc.update_server_config(config) result = director_svc.update_server_config(config)
@@ -947,6 +955,8 @@ def register_api_routes(app, services, settings):
return result, 200, {'Content-Type': 'application/json'} return result, 200, {'Content-Type': 'application/json'}
except Exception as e: except Exception as e:
if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower():
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/clear_config', methods=['POST']) @app.route('/api/director/clear_config', methods=['POST'])
@@ -954,13 +964,15 @@ def register_api_routes(app, services, settings):
def director_clear_config(): def director_clear_config():
try: try:
if not director_svc: if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 500 return jsonify({'success': False, 'error': 'Director service not available'}), 503
map_name = request.get_data(as_text=True).strip() map_name = request.get_data(as_text=True).strip()
result = director_svc.clear_map_config(map_name) result = director_svc.clear_map_config(map_name)
if map_name: if map_name:
director_svc.update_ini_section(map_name, {}, remove_section=True) director_svc.update_ini_section(map_name, {}, remove_section=True)
return result, 200, {'Content-Type': 'application/json'} return result, 200, {'Content-Type': 'application/json'}
except Exception as e: except Exception as e:
if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower():
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/character_transfer', methods=['GET']) @app.route('/api/director/character_transfer', methods=['GET'])
@@ -968,10 +980,12 @@ def register_api_routes(app, services, settings):
def director_character_transfer_get(): def director_character_transfer_get():
try: try:
if not director_svc: if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 500 return jsonify({'success': False, 'error': 'Director service not available'}), 503
data = director_svc.fetch_character_transfer_rules() data = director_svc.fetch_character_transfer_rules()
return data, 200, {'Content-Type': 'application/json'} return data, 200, {'Content-Type': 'application/json'}
except Exception as e: except Exception as e:
if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower():
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/character_transfer', methods=['POST']) @app.route('/api/director/character_transfer', methods=['POST'])
@@ -979,7 +993,7 @@ def register_api_routes(app, services, settings):
def director_character_transfer_update(): def director_character_transfer_update():
try: try:
if not director_svc: if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 500 return jsonify({'success': False, 'error': 'Director service not available'}), 503
config = request.get_json() config = request.get_json()
result = director_svc.update_character_transfer(config) result = director_svc.update_character_transfer(config)
@@ -989,6 +1003,8 @@ def register_api_routes(app, services, settings):
return result, 200, {'Content-Type': 'application/json'} return result, 200, {'Content-Type': 'application/json'}
except Exception as e: except Exception as e:
if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower():
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/character_transfer_clear', methods=['POST']) @app.route('/api/director/character_transfer_clear', methods=['POST'])
@@ -996,11 +1012,13 @@ def register_api_routes(app, services, settings):
def director_character_transfer_clear(): def director_character_transfer_clear():
try: try:
if not director_svc: if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 500 return jsonify({'success': False, 'error': 'Director service not available'}), 503
result = director_svc.clear_character_transfer_overrides() result = director_svc.clear_character_transfer_overrides()
director_svc.update_ini_section('CharacterTransfers', {}, remove_section=True) director_svc.update_ini_section('CharacterTransfers', {}, remove_section=True)
return result, 200, {'Content-Type': 'application/json'} return result, 200, {'Content-Type': 'application/json'}
except Exception as e: except Exception as e:
if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower():
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
# Update management # Update management
+13 -2
View File
@@ -380,13 +380,24 @@ print(json.dumps(s))
# Summary # Summary
Write-Host "============================================================" -ForegroundColor Cyan Write-Host "============================================================" -ForegroundColor Cyan
if ($issues -eq 0) { if ($issues -eq 0) {
Write-Host " All checks passed! The dashboard should work." -ForegroundColor Green Write-Host " All local checks passed!" -ForegroundColor Green
} else { } else {
Write-Host " Found $issues issue(s) that may prevent the dashboard from working." -ForegroundColor Yellow Write-Host " Found $issues local issue(s) that may prevent the dashboard from working." -ForegroundColor Yellow
Write-Host " Review the messages above for details on how to fix each issue." -ForegroundColor Yellow Write-Host " Review the messages above for details on how to fix each issue." -ForegroundColor Yellow
} }
Write-Host "" Write-Host ""
# Server-side diagnostics
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
if ($settings.server -and $settings.server.host -and $settings.server.host -ne 'YOUR_SERVER_IP') {
Write-Host " Running server-side diagnostics..." -ForegroundColor Yellow
Write-Host ""
python (Join-Path $ProjectRoot "scripts\diagnostic.py") (Join-Path $ProjectRoot "settings.yaml")
Write-Host ""
}
}
# Offer port forward guide # Offer port forward guide
Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan
$showGuide = Read-Host " " $showGuide = Read-Host " "
+246
View File
@@ -0,0 +1,246 @@
"""Dune Dashboard Diagnostic Script
Tests connectivity to all critical services:
- SSH to game server VM
- Database port-forward
- Director port-forward
- BGD pod status and logs
- RabbitMQ pods
- Kubernetes namespace access
Usage:
python scripts/diagnostic.py [settings.yaml]
"""
import sys
import os
import subprocess
import json
try:
import yaml
except ImportError:
print("[ERROR] PyYAML not installed. Run: pip install pyyaml")
sys.exit(1)
def load_settings(path):
with open(path) as f:
return yaml.safe_load(f)
def run_cmd(cmd, timeout=15):
try:
result = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=timeout
)
return result.returncode, result.stdout.strip(), result.stderr.strip()
except subprocess.TimeoutExpired:
return -1, "", "Command timed out"
except Exception as e:
return -1, "", str(e)
def check_ssh(settings):
print("\n[1/6] Checking SSH connection...")
host = settings['server']['host']
ssh_key = os.path.expandvars(settings['server'].get('ssh_key', ''))
ssh_user = settings['server'].get('ssh_user', 'dune')
rc, out, err = run_cmd(
f'ssh -i "{ssh_key}" -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes {ssh_user}@{host} "echo OK"',
timeout=15
)
if rc == 0 and 'OK' in out:
print(" [OK] SSH connection successful")
return True
else:
print(f" [FAIL] SSH failed: {err or out}")
return False
def check_namespace(settings):
print("\n[2/6] Checking Kubernetes namespace...")
ns = settings.get('kubernetes', {}).get('namespace', '')
if not ns:
print(" [FAIL] Kubernetes namespace not set in settings.yaml")
return False
host = settings['server']['host']
ssh_key = os.path.expandvars(settings['server'].get('ssh_key', ''))
ssh_user = settings['server'].get('ssh_user', 'dune')
rc, out, err = run_cmd(
f'ssh -i "{ssh_key}" -o StrictHostKeyChecking=no -o ConnectTimeout=10 {ssh_user}@{host} "sudo kubectl get namespace {ns}"',
timeout=15
)
if rc == 0 and ns in out:
print(f" [OK] Namespace '{ns}' exists")
return True
else:
print(f" [FAIL] Namespace '{ns}' not found: {err or out}")
return False
def check_db_port_forward(settings):
print("\n[3/6] Checking database port-forward...")
port = settings.get('server', {}).get('port', 15432)
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
try:
sock.connect(('127.0.0.1', port))
sock.close()
print(f" [OK] Database port-forward listening on localhost:{port}")
return True
except Exception:
print(f" [FAIL] Cannot connect to localhost:{port}")
print(" Make sure the launcher started the SSH tunnel and port-forward")
return False
def check_director_port_forward(settings):
print("\n[4/6] Checking director port-forward...")
port = settings.get('director', {}).get('port', 32479)
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
try:
sock.connect(('127.0.0.1', port))
sock.close()
print(f" [OK] Director port-forward listening on localhost:{port}")
import urllib.request
try:
r = urllib.request.urlopen(f'http://127.0.0.1:{port}/v0/battlegroup', timeout=5)
data = json.loads(r.read())
print(f" [OK] Director API responding (battlegroup loaded)")
return True
except Exception as e:
print(f" [WARN] Director port open but API not responding: {e}")
print(" The BGD pod may be starting or have internal errors")
return False
except Exception:
print(f" [FAIL] Cannot connect to localhost:{port}")
print(" Make sure the launcher started the director port-forward")
return False
def check_bgd_pod(settings):
print("\n[5/6] Checking BGD pod status...")
host = settings['server']['host']
ssh_key = os.path.expandvars(settings['server'].get('ssh_key', ''))
ssh_user = settings['server'].get('ssh_user', 'dune')
ns = settings.get('kubernetes', {}).get('namespace', '')
rc, out, err = run_cmd(
f'ssh -i "{ssh_key}" -o StrictHostKeyChecking=no -o ConnectTimeout=10 {ssh_user}@{host} "sudo kubectl get pods -n {ns} | grep bgd"',
timeout=15
)
if not out:
print(" [FAIL] No BGD pod found")
print(" The battlegroup director deployment may be scaled to 0")
return False
for line in out.split('\n'):
parts = line.split()
if len(parts) >= 3:
name = parts[0]
ready = parts[1]
status = parts[2]
if 'Running' in status and '1/1' in ready:
print(f" [OK] BGD pod running: {name} (ready={ready})")
else:
print(f" [WARN] BGD pod issue: {name} (ready={ready}, status={status})")
if 'CrashLoopBackOff' in out:
print("\n BGD pod is crash looping. Checking recent logs:")
rc, logs, _ = run_cmd(
f'ssh -i "{ssh_key}" -o StrictHostKeyChecking=no -o ConnectTimeout=10 {ssh_user}@{host} "sudo kubectl logs -n {ns} -l app={ns}-bgd-deploy --tail=20"',
timeout=30
)
if logs:
for line in logs.split('\n')[-10:]:
print(f" {line}")
return 'Running' in out
def check_rabbitmq(settings):
print("\n[6/6] Checking RabbitMQ pods...")
host = settings['server']['host']
ssh_key = os.path.expandvars(settings['server'].get('ssh_key', ''))
ssh_user = settings['server'].get('ssh_user', 'dune')
ns = settings.get('kubernetes', {}).get('namespace', '')
rc, out, err = run_cmd(
f'ssh -i "{ssh_key}" -o StrictHostKeyChecking=no -o ConnectTimeout=10 {ssh_user}@{host} "sudo kubectl get pods -n {ns} | grep mq"',
timeout=15
)
if not out:
print(" [FAIL] No RabbitMQ pods found")
return False
all_ok = True
for line in out.split('\n'):
parts = line.split()
if len(parts) >= 3:
name = parts[0]
ready = parts[1]
status = parts[2]
if 'Running' in status:
print(f" [OK] RabbitMQ running: {name} (ready={ready})")
else:
print(f" [WARN] RabbitMQ issue: {name} (ready={ready}, status={status})")
all_ok = False
return all_ok
def main():
settings_path = sys.argv[1] if len(sys.argv) > 1 else 'settings.yaml'
if not os.path.exists(settings_path):
print(f"[ERROR] Settings file not found: {settings_path}")
sys.exit(1)
print("=" * 60)
print(" Dune Awakening Dashboard - Diagnostic Tool")
print("=" * 60)
settings = load_settings(settings_path)
results = []
results.append(("SSH Connection", check_ssh(settings)))
results.append(("Kubernetes Namespace", check_namespace(settings)))
results.append(("Database Port-Forward", check_db_port_forward(settings)))
results.append(("Director Port-Forward", check_director_port_forward(settings)))
results.append(("BGD Pod", check_bgd_pod(settings)))
results.append(("RabbitMQ", check_rabbitmq(settings)))
print("\n" + "=" * 60)
print(" Summary")
print("=" * 60)
passed = sum(1 for _, ok in results if ok)
total = len(results)
for name, ok in results:
status = "[OK]" if ok else "[FAIL]"
print(f" {status} {name}")
print(f"\n {passed}/{total} checks passed")
if passed < total:
print("\n Troubleshooting tips:")
print(" - Restart the launcher to re-establish port-forwards")
print(" - Check BGD logs: sudo kubectl logs -n <ns> -l app=<ns>-bgd-deploy --tail=50")
print(" - If RabbitMQ auth fails, try restarting the full battlegroup")
print(" - Run the launcher with verbose output for more details")
sys.exit(0 if passed == total else 1)
if __name__ == '__main__':
main()
+18 -2
View File
@@ -334,13 +334,29 @@ print(s.get('dashboard', {}).get('port', 5050))
# Summary # Summary
echo "============================================================" echo "============================================================"
if [ $issues -eq 0 ]; then if [ $issues -eq 0 ]; then
echo " All checks passed! The dashboard should work." echo " All local checks passed!"
else else
echo " Found $issues issue(s) that may prevent the dashboard from working." echo " Found $issues local issue(s) that may prevent the dashboard from working."
echo " Review the messages above for details on how to fix each issue." echo " Review the messages above for details on how to fix each issue."
fi fi
echo "" echo ""
# Server-side diagnostics
if [ -f "$settings_file" ]; then
server_host_check=$($PYTHON -c "
import yaml
with open('$settings_file') as f:
s = yaml.safe_load(f) or {}
print(s.get('server', {}).get('host', 'NOT SET'))
" 2>/dev/null)
if [ "$server_host_check" != "NOT SET" ] && [ "$server_host_check" != "YOUR_SERVER_IP" ]; then
echo " Running server-side diagnostics..."
echo ""
$PYTHON "$PROJECT_ROOT/scripts/diagnostic.py" "$settings_file"
echo ""
fi
fi
# Offer port forward guide # Offer port forward guide
echo " Would you like to see the Port Forwarding & Firewall guide? (y/N)" echo " Would you like to see the Port Forwarding & Firewall guide? (y/N)"
read -r show_guide read -r show_guide
+58 -2
View File
@@ -8,7 +8,30 @@
</div> </div>
<div id="loading-banner" class="loading-banner">Loading Director data...</div> <div id="loading-banner" class="loading-banner">Loading Director data...</div>
<div id="error-banner" class="error-banner danger" style="display:none;"></div> <div id="error-banner" class="error-banner" style="display:none;"></div>
<div id="unavailable-banner" class="unavailable-banner" style="display:none;">
<div class="unavailable-icon">&#9888;</div>
<div class="unavailable-content">
<h3>Director Unavailable</h3>
<p id="unavailable-detail">The Battlegroup Director service is not responding.</p>
<div class="unavailable-hints">
<p><strong>Common causes:</strong></p>
<ul>
<li>BGD pod is still starting up (wait 1-2 minutes)</li>
<li>RabbitMQ authentication failure (check pod logs)</li>
<li>Database connectivity issue inside the cluster</li>
<li>BGD pod crashed (check with <code>kubectl get pods</code>)</li>
</ul>
<p><strong>Quick checks (SSH into server):</strong></p>
<ul>
<li><code>sudo kubectl get pods -n &lt;namespace&gt; | grep bgd</code></li>
<li><code>sudo kubectl logs -n &lt;namespace&gt; -l app=&lt;namespace&gt;-bgd-deploy --tail=50</code></li>
<li><code>sudo kubectl get pods -n &lt;namespace&gt; | grep mq</code></li>
</ul>
</div>
<button id="btn-retry-director" class="btn-retry">Retry</button>
</div>
</div>
<div id="director-content" style="display:none;"> <div id="director-content" style="display:none;">
@@ -101,6 +124,18 @@
<style> <style>
.loading-banner { padding: 20px; text-align: center; color: var(--text-muted); font-size: 14px; } .loading-banner { padding: 20px; text-align: center; color: var(--text-muted); font-size: 14px; }
.error-banner { padding: 12px 16px; background: rgba(220, 38, 38, 0.15); border: 1px solid rgba(220, 38, 38, 0.4); border-left: 4px solid #dc2626; border-radius: 6px; color: var(--text); font-size: 13px; margin-bottom: 16px; }
.unavailable-banner { padding: 20px; background: rgba(234, 179, 8, 0.1); border: 1px solid rgba(234, 179, 8, 0.4); border-left: 4px solid #eab308; border-radius: 8px; color: var(--text); text-align: center; margin-bottom: 16px; }
.unavailable-icon { font-size: 48px; color: #eab308; margin-bottom: 12px; }
.unavailable-content h3 { margin: 0 0 8px; font-size: 18px; color: var(--text); }
.unavailable-content > p { margin: 0 0 16px; color: var(--text-light); font-size: 14px; }
.unavailable-hints { text-align: left; background: var(--bg); border-radius: 6px; padding: 16px; margin: 0 auto 16px; max-width: 600px; font-size: 13px; }
.unavailable-hints p { margin: 8px 0 4px; }
.unavailable-hints ul { margin: 4px 0 12px; padding-left: 20px; }
.unavailable-hints li { margin: 4px 0; color: var(--text-light); }
.unavailable-hints code { background: var(--card-bg); padding: 2px 6px; border-radius: 3px; font-size: 12px; color: var(--text); }
.btn-retry { padding: 8px 24px; background: #eab308; color: #1a1a1a; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 600; }
.btn-retry:hover { background: #ca8a04; }
.mb-3 { margin-bottom: 16px; } .mb-3 { margin-bottom: 16px; }
.map-card { background: var(--card-bg); border-radius: 12px; box-shadow: var(--shadow); margin-bottom: 12px; overflow: hidden; } .map-card { background: var(--card-bg); border-radius: 12px; box-shadow: var(--shadow); margin-bottom: 12px; overflow: hidden; }
.map-header { padding: 10px 16px; background: var(--bg-hover); display: flex; justify-content: space-between; align-items: center; cursor: pointer; user-select: none; } .map-header { padding: 10px 16px; background: var(--bg-hover); display: flex; justify-content: space-between; align-items: center; cursor: pointer; user-select: none; }
@@ -154,13 +189,27 @@ let charTransferData = null;
async function loadDirector() { async function loadDirector() {
const banner = document.getElementById('loading-banner'); const banner = document.getElementById('loading-banner');
const error = document.getElementById('error-banner'); const error = document.getElementById('error-banner');
const unavailable = document.getElementById('unavailable-banner');
const content = document.getElementById('director-content'); const content = document.getElementById('director-content');
try { try {
const [bgResp, ctResp] = await Promise.all([ const [bgResp, ctResp] = await Promise.all([
fetch('/api/director/battlegroup'), fetch('/api/director/battlegroup'),
fetch('/api/director/character_transfer') fetch('/api/director/character_transfer')
]); ]);
if (!bgResp.ok) throw new Error('Failed to load battlegroup data'); if (!bgResp.ok) {
const errData = await bgResp.json().catch(() => null);
if (bgResp.status === 503 && errData && errData.detail) {
banner.style.display = 'none';
error.style.display = 'none';
content.style.display = 'none';
unavailable.style.display = 'block';
document.getElementById('unavailable-detail').textContent = errData.detail;
return;
}
throw new Error(errData?.error || 'Failed to load battlegroup data');
}
unavailable.style.display = 'none';
error.style.display = 'none';
bgData = await bgResp.json(); bgData = await bgResp.json();
if (ctResp.ok) { if (ctResp.ok) {
charTransferData = await ctResp.json(); charTransferData = await ctResp.json();
@@ -177,11 +226,18 @@ async function loadDirector() {
} }
} catch (e) { } catch (e) {
banner.style.display = 'none'; banner.style.display = 'none';
unavailable.style.display = 'none';
error.textContent = 'Error loading Director: ' + e.message; error.textContent = 'Error loading Director: ' + e.message;
error.style.display = 'block'; error.style.display = 'block';
} }
} }
document.getElementById('btn-retry-director')?.addEventListener('click', () => {
document.getElementById('unavailable-banner').style.display = 'none';
document.getElementById('loading-banner').style.display = 'block';
loadDirector();
});
function updateStats() { function updateStats() {
const t = calcTotals(); const t = calcTotals();
document.getElementById('stat-players').textContent = t.total; document.getElementById('stat-players').textContent = t.total;