fix: director ConfigMap name, CSRF, ServerSetScale replicas + error handling
- Fix ConfigMap name derivation (strip funcom-seabass- prefix from namespace) - Fix CSRF token missing on all 6 director POST handlers (fetch -> csrfFetch) - Add ServerSetScale replicas management to director map cards - Merge webOverrideCfg into cfg so UI shows active runtime overrides - Auto-refresh after Apply and reset button state on all handlers - Surface JSON error bodies in error banner instead of silent fail - Fix SSL SAN handling for IP vs DNS common name - Fix Let's Encrypt certbot paths to use project-root certbot/ dir - Fix deploys_ok to reflect actual K8s availability - Add active server deployment matching with restart buttons
This commit is contained in:
1 parent
0f173dc107
commit
7ed7d5de5c
8 files changed
+321
-57
No files matched your search
@@ -38,6 +38,9 @@ internal-scripts/ssh/sshKey
|
||||
# SSL Certificates
|
||||
ssl/
|
||||
|
||||
# Let's Encrypt certbot runtime data
|
||||
certbot/
|
||||
|
||||
# Temporary settings scripts (generated by launcher)
|
||||
read_settings*.py
|
||||
hash_pw*.py
|
||||
|
||||
+37
-1
@@ -922,7 +922,8 @@ def register_api_routes(app, services, settings):
|
||||
if map_name:
|
||||
kv = director_svc.extract_server_config_kv(config)
|
||||
if kv:
|
||||
director_svc.update_ini_section(map_name, kv)
|
||||
if not director_svc.update_ini_section(map_name, kv):
|
||||
logger.warning("ConfigMap update failed for map %s (director API call succeeded)", map_name)
|
||||
|
||||
return result, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
@@ -992,6 +993,41 @@ def register_api_routes(app, services, settings):
|
||||
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/server_set_scale/<map_name>')
|
||||
@auth_req
|
||||
def director_server_set_scale_get(map_name):
|
||||
try:
|
||||
if not director_svc:
|
||||
return jsonify({'success': False, 'error': 'Director service not available'}), 503
|
||||
scale = director_svc.get_server_set_scale(map_name)
|
||||
if scale is None:
|
||||
return jsonify({'replicas': 0, 'partitions': []})
|
||||
spec = scale.get('spec', {})
|
||||
return jsonify({
|
||||
'replicas': spec.get('replicas', 0),
|
||||
'partitions': [p for p in spec.get('partitions', []) if p is not None],
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/server_set_scale/<map_name>', methods=['POST'])
|
||||
@auth_req
|
||||
def director_server_set_scale_patch(map_name):
|
||||
try:
|
||||
if not director_svc:
|
||||
return jsonify({'success': False, 'error': 'Director service not available'}), 503
|
||||
config = request.get_json()
|
||||
replicas = int(config.get('replicas', 1))
|
||||
partitions_raw = config.get('partitions', [])
|
||||
partitions = [int(p) for p in partitions_raw if p is not None]
|
||||
if replicas > len(partitions):
|
||||
return jsonify({'success': False, 'error': 'replicas cannot exceed partition count'}), 400
|
||||
if not director_svc.patch_server_set_scale(map_name, replicas, partitions):
|
||||
return jsonify({'success': False, 'error': 'Failed to patch ServerSetScale'}), 500
|
||||
return jsonify({'success': True})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
# Update management
|
||||
@app.route('/api/update/status')
|
||||
@auth_req
|
||||
|
||||
+30
-2
@@ -426,7 +426,7 @@ def register_routes(app, services, settings):
|
||||
def server_status():
|
||||
logger.debug(f"Page access: /server by user={current_user.id}")
|
||||
try:
|
||||
active_servers = db.query("""
|
||||
active_servers_raw = db.query("""
|
||||
SELECT server_id, map
|
||||
FROM dune.world_partition
|
||||
WHERE server_id IS NOT NULL
|
||||
@@ -448,6 +448,34 @@ def register_routes(app, services, settings):
|
||||
deployments = k8s.get_deployments()
|
||||
node_metrics = k8s.get_node_metrics()
|
||||
|
||||
active_servers = []
|
||||
for s in active_servers_raw:
|
||||
sid = (s.get('server_id') or '').lower().replace('_', '-')
|
||||
s['deployment'] = ''
|
||||
mp = (s.get('map') or '').lower().replace('_', '-')
|
||||
for d in deployments:
|
||||
short = d.replace('deployment.apps/', '')
|
||||
if sid and sid in short.lower():
|
||||
s['deployment'] = d
|
||||
break
|
||||
if mp and mp in short.lower():
|
||||
s['deployment'] = d
|
||||
break
|
||||
if not s['deployment']:
|
||||
mid = '-sg-' + sid
|
||||
for d in deployments:
|
||||
short = d.replace('deployment.apps/', '')
|
||||
if mid in short.lower():
|
||||
s['deployment'] = d
|
||||
break
|
||||
if not s['deployment'] and mp:
|
||||
for d in deployments:
|
||||
short = d.replace('deployment.apps/', '')
|
||||
if mp in short.lower() and 'pod' in short.lower():
|
||||
s['deployment'] = d
|
||||
break
|
||||
active_servers.append(s)
|
||||
|
||||
for p in partitions:
|
||||
sid = (p.get('server_id') or '').lower().replace('_', '-')
|
||||
p['deployment'] = ''
|
||||
@@ -482,7 +510,7 @@ def register_routes(app, services, settings):
|
||||
online_players=online_players, partitions=partitions,
|
||||
overmap_count=overmap_count.get('c') if overmap_count else 0,
|
||||
online_count=online_count.get('c') if online_count else 0,
|
||||
deployments=deployments, deploys_ok=True, ssh_error='',
|
||||
deployments=deployments, deploys_ok=len(deployments) > 0, ssh_error='',
|
||||
node_metrics=node_metrics)
|
||||
except Exception as e:
|
||||
logger.exception("Error in server_status route")
|
||||
|
||||
@@ -27,7 +27,13 @@ class DirectorService:
|
||||
self.k8s = k8s_service
|
||||
self.ssh = ssh_service
|
||||
self.namespace = namespace
|
||||
self.cm_name = f"{namespace}-bgd-conf-cm"
|
||||
resource_prefix = namespace
|
||||
for prefix in ['funcom-seabass-']:
|
||||
if resource_prefix.startswith(prefix):
|
||||
resource_prefix = resource_prefix[len(prefix):]
|
||||
break
|
||||
self.resource_prefix = resource_prefix
|
||||
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
||||
|
||||
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
||||
timeout: int = 15, raw_data: bool = False) -> str:
|
||||
@@ -141,8 +147,9 @@ class DirectorService:
|
||||
Returns:
|
||||
True if the update succeeded, False otherwise.
|
||||
"""
|
||||
cm_out, _, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
|
||||
cm_out, cm_err, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
|
||||
if cm_rc != 0 or not cm_out:
|
||||
logger.warning("update_ini_section: could not get ConfigMap %s: %s", self.cm_name, cm_err)
|
||||
return False
|
||||
|
||||
cm = json.loads(cm_out)
|
||||
@@ -165,6 +172,39 @@ class DirectorService:
|
||||
cfg.write(buf)
|
||||
return self.patch_configmap(buf.getvalue())
|
||||
|
||||
# ── ServerSetScale management ────────────────────────────────────
|
||||
|
||||
def _map_to_scale_name(self, map_name: str) -> str:
|
||||
safe = map_name.lower().replace('_', '-')
|
||||
return f"{self.resource_prefix}-{safe}"
|
||||
|
||||
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||
name = self._map_to_scale_name(map_name)
|
||||
cm_out, cm_err, cm_rc = self.k8s.run(
|
||||
f'get serversetscale {name} -o json')
|
||||
if cm_rc != 0 or not cm_out:
|
||||
return None
|
||||
return json.loads(cm_out)
|
||||
|
||||
def patch_server_set_scale(self, map_name: str, replicas: int,
|
||||
partitions: list) -> bool:
|
||||
name = self._map_to_scale_name(map_name)
|
||||
patch = json.dumps({
|
||||
'spec': {
|
||||
'partitions': partitions,
|
||||
'replicas': replicas,
|
||||
}
|
||||
})
|
||||
patch_b64 = base64.b64encode(patch.encode()).decode()
|
||||
cmd = (f'echo {patch_b64} | base64 -d | '
|
||||
f'sudo kubectl patch serversetscale {name} -n {self.namespace} '
|
||||
f'--type merge --patch-file /dev/stdin')
|
||||
out, err, rc = self.ssh.run(cmd, timeout=15)
|
||||
if rc != 0:
|
||||
logger.warning("ServerSetScale patch failed for %s: %s", map_name, err)
|
||||
return False
|
||||
return True
|
||||
|
||||
# ── Helper: extract config values for INI update ─────────────────
|
||||
|
||||
@staticmethod
|
||||
|
||||
+6
-1
@@ -108,7 +108,12 @@ def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None,
|
||||
])
|
||||
|
||||
# Build SAN entries
|
||||
san_entries = [x509.DNSName(common_name)]
|
||||
san_entries = []
|
||||
# Add common_name as the appropriate SAN type
|
||||
try:
|
||||
san_entries.append(x509.IPAddress(ipaddress.ip_address(common_name)))
|
||||
except ValueError:
|
||||
san_entries.append(x509.DNSName(common_name))
|
||||
if san_ips:
|
||||
for ip in san_ips:
|
||||
try:
|
||||
|
||||
+19
-11
@@ -1535,6 +1535,9 @@ function Run-Setup {
|
||||
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
|
||||
$CertDir = Join-Path $ProjectRoot "ssl"
|
||||
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
|
||||
$LeConfigDir = Join-Path $ProjectRoot "certbot\config"
|
||||
$LeWorkDir = Join-Path $ProjectRoot "certbot\work"
|
||||
$LeLogsDir = Join-Path $ProjectRoot "certbot\logs"
|
||||
$CaCertPath = Join-Path $CertDir "ca.pem"
|
||||
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
|
||||
$SslCertPath = Join-Path $CertDir "cert.pem"
|
||||
@@ -1581,8 +1584,14 @@ function Run-Setup {
|
||||
|
||||
$certbotUseModule = ($certbotCmd.Source -eq "python")
|
||||
|
||||
New-Item -ItemType Directory -Path $LeConfigDir -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $LeWorkDir -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $LeLogsDir -Force | Out-Null
|
||||
|
||||
$certbotDirArgs = @("--config-dir", $LeConfigDir, "--work-dir", $LeWorkDir, "--logs-dir", $LeLogsDir)
|
||||
|
||||
if ($certbotUseModule) {
|
||||
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos")
|
||||
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos") + $certbotDirArgs
|
||||
if ($LeEmail) {
|
||||
$certbotArgs += "--email"
|
||||
$certbotArgs += $LeEmail
|
||||
@@ -1596,7 +1605,7 @@ function Run-Setup {
|
||||
"-d", $DomainName,
|
||||
"--non-interactive",
|
||||
"--agree-tos"
|
||||
)
|
||||
) + $certbotDirArgs
|
||||
if ($LeEmail) {
|
||||
$certbotArgs += "--email"
|
||||
$certbotArgs += $LeEmail
|
||||
@@ -1609,13 +1618,9 @@ function Run-Setup {
|
||||
|
||||
if ($certbotResult.ExitCode -eq 0) {
|
||||
$UseLetsEncrypt = $true
|
||||
$LeCertPath = "C:\ProgramData\certbot\live\$DomainName\fullchain.pem"
|
||||
$LeKeyPath = "C:\ProgramData\certbot\live\$DomainName\privkey.pem"
|
||||
|
||||
if (-not (Test-Path $LeCertPath)) {
|
||||
$LeCertPath = "C:\Certbot\live\$DomainName\fullchain.pem"
|
||||
$LeKeyPath = "C:\Certbot\live\$DomainName\privkey.pem"
|
||||
}
|
||||
$LeLiveDir = Join-Path $LeConfigDir "live\$DomainName"
|
||||
$LeCertPath = Join-Path $LeLiveDir "fullchain.pem"
|
||||
$LeKeyPath = Join-Path $LeLiveDir "privkey.pem"
|
||||
|
||||
if (Test-Path $LeCertPath) {
|
||||
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
|
||||
@@ -1654,8 +1659,11 @@ function Run-Setup {
|
||||
}
|
||||
|
||||
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
|
||||
$SanDnsArray = "['localhost'"
|
||||
if ($DomainName) { $SanDnsArray += ", '" + $DomainName + "'" }
|
||||
$SanDnsArray += "]"
|
||||
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
|
||||
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=['localhost'])"
|
||||
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=$SanDnsArray)"
|
||||
$SslCert = "'$SslCertPath'"
|
||||
$SslKey = "'$SslKeyPath'"
|
||||
|
||||
@@ -1787,7 +1795,7 @@ function Run-Setup {
|
||||
$certbotPath = "certbot"
|
||||
}
|
||||
|
||||
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet"
|
||||
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet --config-dir `"$LeConfigDir`" --work-dir `"$LeWorkDir`" --logs-dir `"$LeLogsDir`""
|
||||
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
|
||||
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
|
||||
|
||||
+110
-19
@@ -185,6 +185,7 @@
|
||||
<script>
|
||||
let bgData = null;
|
||||
let charTransferData = null;
|
||||
let scaleData = {};
|
||||
|
||||
async function loadDirector() {
|
||||
const banner = document.getElementById('loading-banner');
|
||||
@@ -214,6 +215,7 @@ async function loadDirector() {
|
||||
if (ctResp.ok) {
|
||||
charTransferData = await ctResp.json();
|
||||
}
|
||||
await loadScaleData(bgData);
|
||||
if (document.getElementById('maps-container').children.length === 0) {
|
||||
renderStats();
|
||||
renderMaps();
|
||||
@@ -238,6 +240,21 @@ document.getElementById('btn-retry-director')?.addEventListener('click', () => {
|
||||
loadDirector();
|
||||
});
|
||||
|
||||
async function loadScaleData(bg) {
|
||||
const maps = [];
|
||||
const addMaps = (obj) => { if (obj) Object.keys(obj).forEach(k => maps.push(k)); };
|
||||
addMaps(bg.dimensionMaps);
|
||||
addMaps(bg.instancedMaps);
|
||||
addMaps(bg.singleServerMaps);
|
||||
const results = await Promise.allSettled(
|
||||
maps.map(m => fetch(`/api/director/server_set_scale/${encodeURIComponent(m)}`).then(r => r.json()))
|
||||
);
|
||||
maps.forEach((m, i) => {
|
||||
const r = results[i];
|
||||
scaleData[m] = (r.status === 'fulfilled') ? r.value : { replicas: 0, partitions: [] };
|
||||
});
|
||||
}
|
||||
|
||||
function updateStats() {
|
||||
const t = calcTotals();
|
||||
document.getElementById('stat-players').textContent = t.total;
|
||||
@@ -301,6 +318,13 @@ function updateMapCards() {
|
||||
const nameSpan = summaryParts[i].querySelector('.name');
|
||||
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
|
||||
}
|
||||
|
||||
const repInput = document.getElementById(`cfg-${mapName}-replicas`);
|
||||
if (repInput) {
|
||||
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||
repInput.value = sc.replicas;
|
||||
repInput.max = sc.partitions.length || 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,7 +405,7 @@ function renderMaps() {
|
||||
}
|
||||
|
||||
function buildMapCard(mapName, mapData, type) {
|
||||
const cfg = mapData.cfg || {};
|
||||
const cfg = { ...(mapData.cfg || {}), ...(mapData.webOverrideCfg || {}) };
|
||||
let serversHtml = '';
|
||||
let configHtml = '';
|
||||
let summaryHtml = '';
|
||||
@@ -505,6 +529,7 @@ function buildDimensionConfig(mapName, cfg) {
|
||||
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
||||
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
||||
const phCap = cfg.playerHardCap ?? '';
|
||||
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||
return `
|
||||
<div class="config-row">
|
||||
<div class="config-field">
|
||||
@@ -527,6 +552,10 @@ function buildDimensionConfig(mapName, cfg) {
|
||||
<label>Scale Throttle (s)</label>
|
||||
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
||||
</div>
|
||||
<div class="config-field">
|
||||
<label>Replicas</label>
|
||||
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
|
||||
</div>
|
||||
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
|
||||
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
||||
</div>
|
||||
@@ -539,6 +568,7 @@ function buildInstancedConfig(mapName, cfg) {
|
||||
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
||||
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
||||
const phCap = cfg.playerHardCap ?? '';
|
||||
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||
return `
|
||||
<div class="config-row">
|
||||
<div class="config-field">
|
||||
@@ -561,6 +591,10 @@ function buildInstancedConfig(mapName, cfg) {
|
||||
<label>Scale Throttle (s)</label>
|
||||
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
||||
</div>
|
||||
<div class="config-field">
|
||||
<label>Replicas</label>
|
||||
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
|
||||
</div>
|
||||
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
|
||||
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
||||
</div>
|
||||
@@ -625,23 +659,45 @@ async function applyConfig(mapName, type, btn) {
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await fetch('/api/director/update_config', {
|
||||
const resp = await csrfFetch('/api/director/update_config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
if (!resp.ok) {
|
||||
let errMsg = `HTTP ${resp.status}`;
|
||||
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
btn.classList.remove('applying');
|
||||
btn.classList.add('applied');
|
||||
btn.textContent = 'Applied!';
|
||||
setTimeout(() => {
|
||||
btn.classList.remove('applied');
|
||||
btn.textContent = 'Apply';
|
||||
btn.disabled = false;
|
||||
}, 2000);
|
||||
btn.disabled = false;
|
||||
|
||||
const replicasInput = document.getElementById(`cfg-${mapName}-replicas`);
|
||||
if (replicasInput && type !== 'single') {
|
||||
const sc = scaleData[mapName] || { partitions: [], replicas: 1 };
|
||||
const newReplicas = parseInt(replicasInput.value) || 1;
|
||||
if (newReplicas !== sc.replicas) {
|
||||
const partInput = document.getElementById(`cfg-${mapName}-partitions`);
|
||||
let partitions = sc.partitions;
|
||||
if (partInput) {
|
||||
try { partitions = JSON.parse('[' + partInput.value + ']'); } catch(_){}
|
||||
}
|
||||
csrfFetch(`/api/director/server_set_scale/${encodeURIComponent(mapName)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ replicas: newReplicas, partitions: partitions })
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(() => { btn.textContent = 'Apply'; btn.classList.remove('applied'); loadDirector(); }, 1200);
|
||||
} catch (e) {
|
||||
btn.classList.remove('applying');
|
||||
btn.textContent = 'Failed';
|
||||
const errDiv = document.getElementById('error-banner');
|
||||
if (errDiv) { errDiv.textContent = 'Config apply error: ' + e.message; errDiv.style.display = 'block'; }
|
||||
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
|
||||
}
|
||||
}
|
||||
@@ -650,15 +706,23 @@ async function clearConfig(mapName, btn) {
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Clearing...';
|
||||
try {
|
||||
const resp = await fetch('/api/director/clear_config', {
|
||||
const resp = await csrfFetch('/api/director/clear_config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'text/plain' },
|
||||
body: mapName
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
if (!resp.ok) {
|
||||
let errMsg = `HTTP ${resp.status}`;
|
||||
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
btn.textContent = 'Cleared!';
|
||||
setTimeout(() => { loadDirector(); }, 1500);
|
||||
btn.disabled = false;
|
||||
setTimeout(() => { btn.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||
} catch (e) {
|
||||
btn.textContent = 'Failed';
|
||||
const errDiv = document.getElementById('error-banner');
|
||||
if (errDiv) { errDiv.textContent = 'Config clear error: ' + e.message; errDiv.style.display = 'block'; }
|
||||
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
|
||||
}
|
||||
}
|
||||
@@ -671,17 +735,24 @@ document.getElementById('btn-apply-world')?.addEventListener('click', async func
|
||||
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
|
||||
};
|
||||
try {
|
||||
const resp = await fetch('/api/director/character_transfer', {
|
||||
const resp = await csrfFetch('/api/director/character_transfer', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
if (!resp.ok) {
|
||||
let errMsg = `HTTP ${resp.status}`;
|
||||
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
|
||||
this.textContent = 'Applied!';
|
||||
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
||||
this.disabled = false;
|
||||
setTimeout(() => { this.textContent = 'Apply'; }, 2000);
|
||||
} catch (e) {
|
||||
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
||||
const errDiv = document.getElementById('error-banner');
|
||||
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
|
||||
this.textContent = 'Apply'; this.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -691,12 +762,19 @@ document.getElementById('btn-clear-world')?.addEventListener('click', async func
|
||||
this.textContent = 'Clearing...';
|
||||
try {
|
||||
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
if (!resp.ok) {
|
||||
let errMsg = `HTTP ${resp.status}`;
|
||||
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
|
||||
this.textContent = 'Cleared!';
|
||||
setTimeout(() => { loadDirector(); }, 1500);
|
||||
this.disabled = false;
|
||||
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||
} catch (e) {
|
||||
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
||||
const errDiv = document.getElementById('error-banner');
|
||||
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
|
||||
this.textContent = 'Clear'; this.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -716,12 +794,18 @@ document.getElementById('btn-apply-transfer')?.addEventListener('click', async f
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
if (!resp.ok) {
|
||||
let errMsg = `HTTP ${resp.status}`;
|
||||
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
|
||||
this.textContent = 'Applied!';
|
||||
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
||||
} catch (e) {
|
||||
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
||||
const errDiv = document.getElementById('error-banner');
|
||||
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
|
||||
this.textContent = 'Apply'; this.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -731,12 +815,19 @@ document.getElementById('btn-clear-transfer')?.addEventListener('click', async f
|
||||
this.textContent = 'Clearing...';
|
||||
try {
|
||||
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
if (!resp.ok) {
|
||||
let errMsg = `HTTP ${resp.status}`;
|
||||
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
|
||||
this.textContent = 'Cleared!';
|
||||
setTimeout(() => { loadDirector(); }, 1500);
|
||||
this.disabled = false;
|
||||
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||
} catch (e) {
|
||||
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
||||
const errDiv = document.getElementById('error-banner');
|
||||
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
|
||||
this.textContent = 'Clear'; this.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
+74
-21
@@ -85,14 +85,28 @@
|
||||
<div class="card-header">Active Server IDs</div>
|
||||
<div class="card-body">
|
||||
{% if active_servers %}
|
||||
<ul style="list-style:none;">
|
||||
{% for s in active_servers %}
|
||||
<li style="padding:4px 0;font-family:monospace;font-size:12px;">
|
||||
<span style="font-weight:600;">{{ s.server_id }}</span>
|
||||
{% if s.map %} — <span style="color:var(--primary);">{{ s.map }}</span>{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Server ID</th><th>Map</th><th>Actions</th></tr></thead>
|
||||
<tbody>
|
||||
{% for s in active_servers %}
|
||||
<tr>
|
||||
<td style="font-family:monospace;font-size:12px;font-weight:600;">{{ s.server_id }}</td>
|
||||
<td style="color:var(--primary);">{{ s.map or '' }}</td>
|
||||
<td>
|
||||
{% if s.deployment %}
|
||||
<button class="partition-btn" data-deploy="{{ s.deployment }}" data-map="{{ s.server_id }}" title="Restart this server's deployment. Players on this map will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
|
||||
{% elif not deployments %}
|
||||
<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>
|
||||
{% else %}
|
||||
<span style="color:var(--text-muted);font-size:11px;">No deploy</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty">No active servers</div>
|
||||
{% endif %}
|
||||
@@ -116,7 +130,7 @@
|
||||
<td>{{ p.dimension_index }}</td>
|
||||
<td>{{ 'Yes' if p.blocked else 'No' }}</td>
|
||||
<td>{{ p.label or '' }}</td>
|
||||
<td>{% if p.deployment %}<button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>{% else %}—{% endif %}</td>
|
||||
<td>{% if p.deployment %}<div style="display:flex;gap:4px;flex-wrap:wrap;"><button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Restart this partition's deployment. Players on this map will disconnect." style="padding:4px 10px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Restart</button><button class="partition-status-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Show rollout status for this partition's deployment." style="padding:4px 10px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Status</button></div>{% elif not deployments %}<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>{% else %}<span style="color:var(--text-muted);font-size:11px;">No deploy</span>{% endif %}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="7" class="empty">No partitions found</td></tr>
|
||||
@@ -137,6 +151,13 @@
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{% if deploys_ok %}
|
||||
<div style="margin-bottom:10px;padding:10px;background:#1a1a2e;border-radius:6px;font-size:12px;line-height:1.5;color:#a0a0b0;">
|
||||
<strong>Button Guide:</strong>
|
||||
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e67e22;">Restart</span> — rolling restart of pods</span>
|
||||
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#3498db;">Status</span> — rollout status</span>
|
||||
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e74c3c;">Scale to 0</span> — stop all pods</span>
|
||||
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#27ae60;">Scale to 1</span> — start a pod</span>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Deployment</th><th>Actions</th></tr></thead>
|
||||
@@ -145,10 +166,10 @@
|
||||
<tr>
|
||||
<td style="font-family:monospace;font-size:13px;">{{ d.replace('deployment.apps/','') }}</td>
|
||||
<td>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="restart" style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="status" style="padding:4px 12px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Status</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_0" style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 0</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="restart" title="Performs a rolling restart of this deployment's pods. Players will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="status" title="Show rollout status: whether the deployment is successfully rolled out, pending, or failed." style="padding:4px 12px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Status</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_0" title="Scale to 0 replicas. Stops all pods for this deployment. Use to shut down a server." style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 0</button>
|
||||
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" title="Scale to 1 replica. Starts a single pod. Use to bring a stopped server back online." style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
@@ -339,7 +360,7 @@ document.querySelectorAll('.partition-btn').forEach(btn => {
|
||||
if (!confirm(`Restart "${map}" partition (${deploy})?`)) return;
|
||||
if (!confirm('Are you sure? Players on this map will be disconnected.')) return;
|
||||
this.disabled = true;
|
||||
this.textContent = 'Restarting...';
|
||||
this.textContent = 'Working...';
|
||||
const output = document.getElementById('action-output');
|
||||
const outputText = document.getElementById('action-output-text');
|
||||
output.style.display = 'block';
|
||||
@@ -359,10 +380,36 @@ document.querySelectorAll('.partition-btn').forEach(btn => {
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('refresh-pods')?.addEventListener('click', async function() {
|
||||
this.disabled = true;
|
||||
this.textContent = 'Loading...';
|
||||
document.querySelectorAll('.partition-status-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async function() {
|
||||
const deploy = this.dataset.deploy;
|
||||
const map = this.dataset.map;
|
||||
const label = this.textContent.trim();
|
||||
this.disabled = true;
|
||||
this.textContent = 'Loading...';
|
||||
const output = document.getElementById('action-output');
|
||||
const outputText = document.getElementById('action-output-text');
|
||||
output.style.display = 'block';
|
||||
outputText.textContent = `Fetching status for ${deploy}...`;
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('deployment', deploy);
|
||||
form.append('action', 'status');
|
||||
const resp = await csrfFetch('/server/action', { method: 'POST', body: form });
|
||||
const data = await resp.json();
|
||||
outputText.textContent = data.output || (data.success ? 'No status output' : 'Failed');
|
||||
} catch (e) {
|
||||
outputText.textContent = 'Error: ' + e.message;
|
||||
}
|
||||
this.disabled = false;
|
||||
this.textContent = label;
|
||||
});
|
||||
});
|
||||
|
||||
async function refreshPods() {
|
||||
const btn = document.getElementById('refresh-pods');
|
||||
const pre = document.getElementById('pods-text');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Loading...'; }
|
||||
pre.textContent = 'Fetching pod list...';
|
||||
try {
|
||||
const resp = await fetch('/server/pods');
|
||||
@@ -371,9 +418,10 @@ document.getElementById('refresh-pods')?.addEventListener('click', async functio
|
||||
} catch (e) {
|
||||
pre.textContent = 'Error: ' + e.message;
|
||||
}
|
||||
this.disabled = false;
|
||||
this.textContent = 'Refresh Pods';
|
||||
});
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Refresh Pods'; }
|
||||
}
|
||||
|
||||
document.getElementById('refresh-pods')?.addEventListener('click', refreshPods);
|
||||
|
||||
async function bgAction(action, btn) {
|
||||
const confirmMsgs = {
|
||||
@@ -603,7 +651,8 @@ debugToggle.addEventListener('change', async function() {
|
||||
try {
|
||||
const resp = await csrfFetch('/api/settings/debug', {
|
||||
method: 'POST',
|
||||
body: { enabled: enabled }
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled: enabled })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.success) {
|
||||
@@ -628,5 +677,9 @@ debugToggle.addEventListener('change', async function() {
|
||||
|
||||
// Load debug status on page load
|
||||
loadDebugStatus();
|
||||
|
||||
// Auto-load battlegroup and pods once on page load, then require manual refresh
|
||||
bgRefreshStatus();
|
||||
refreshPods();
|
||||
</script>
|
||||
{% endblock %}
|
||||
Reference in new issue
Block a user