Console update

This commit is contained in:
2026-03-06 21:24:56 +01:00
parent 92aa7b3f77
commit 6620158531
4 changed files with 504 additions and 164 deletions

View File

@@ -9,6 +9,7 @@ $terminalNotice = null;
$terminalError = null;
$terminalUrl = null;
$terminalToken = null;
$terminalHostLabel = null;
$settings = modules()->settings('pi_control');
$ttydUrl = trim((string)($settings['ttyd_url'] ?? '/ttyd'));
@@ -22,18 +23,76 @@ $tokenTtl = $tokenTtl > 0 ? $tokenTtl : 10;
$hosts = $pdo->query('SELECT * FROM ' . $table('hosts') . ' ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);
$commands = $pdo->query('SELECT * FROM ' . $table('commands') . ' ORDER BY label ASC')->fetchAll(PDO::FETCH_ASSOC);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = (string)($_POST['action'] ?? '');
$renderRuns = function (array $runs): string {
ob_start();
if (!$runs) {
echo '<tr><td colspan="7" class="muted">Noch keine Runs.</td></tr>';
return ob_get_clean();
}
foreach ($runs as $r) {
$out = (string)($r['output'] ?? '');
$err = (string)($r['error'] ?? '');
$snippet = $out !== '' ? $out : $err;
if (strlen($snippet) > 140) {
$snippet = substr($snippet, 0, 140) . '…';
}
echo '<tr>';
echo '<td>' . e((string)$r['id']) . '</td>';
echo '<td>' . e((string)($r['status'] ?? '')) . '</td>';
echo '<td>' . e((string)($r['host_name'] ?? $r['host_addr'] ?? '')) . '</td>';
echo '<td class="muted" style="max-width:360px;"><code>' . e((string)($r['command_text'] ?? '')) . '</code></td>';
echo '<td>' . e((string)($r['created_by'] ?? '')) . '</td>';
echo '<td class="muted" style="max-width:240px;"><code>' . e($snippet) . '</code></td>';
echo '<td>' . (!empty($r['timeout_sec']) ? e((string)$r['timeout_sec']) . 's' : 'default') . '</td>';
echo '</tr>';
}
return ob_get_clean();
};
if ($action === 'open_console') {
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
$provider = 'ttyd';
if (isset($_GET['queue_json'])) {
$runs = $pdo->query(
'SELECT r.*, h.name AS host_name, h.host AS host_addr
FROM ' . $table('runs') . ' r
LEFT JOIN ' . $table('hosts') . ' h ON h.id = r.host_id
ORDER BY r.id DESC LIMIT 20'
)->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => true,
'next' => 10,
'html' => $renderRuns($runs),
]);
exit;
}
if ($hostId <= 0) {
$terminalError = 'Bitte einen Host wählen.';
} elseif ($ttydUrl === '') {
$terminalError = 'ttyd URL fehlt. Bitte im Setup setzen.';
} else {
if (isset($_GET['open_console_json'])) {
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
$presetId = (int)($_POST['terminal_preset_id'] ?? 0);
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
$terminalError = null;
$terminalUrl = null;
$terminalToken = null;
$terminalHostLabel = null;
if ($hostId <= 0) {
$terminalError = 'Bitte einen Host wählen.';
} elseif ($ttydUrl === '') {
$terminalError = 'ttyd URL fehlt. Bitte im Setup setzen.';
} else {
$presetCommand = '';
if ($presetId > 0) {
foreach ($commands as $c) {
if ((int)$c['id'] === $presetId) {
if (!auth_is_admin() && !empty($c['admin_only'])) {
$terminalError = 'Diese Vorlage ist nur für Admins.';
} else {
$presetCommand = (string)$c['command'];
}
break;
}
}
}
if (!$terminalError) {
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
$expiresSql = $driver === 'pgsql'
? "NOW() + INTERVAL '{$tokenTtl} minutes'"
@@ -48,88 +107,122 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$stmt->execute([
'token' => $token,
'host_id' => $hostId,
'provider' => $provider,
'provider' => 'ttyd',
'created_by' => auth_display_name() ?: null,
]);
$sep = str_contains($ttydUrl, '?') ? '&' : '?';
$terminalUrl = rtrim($ttydUrl, '/') . '/' . $sep . 'arg=' . rawurlencode($token);
}
} else {
$hostId = (int)($_POST['host_id'] ?? 0);
$commandId = (int)($_POST['command_id'] ?? 0);
$rawCommand = trim((string)($_POST['command_text'] ?? ''));
$timeoutSec = $defaultTimeout;
if ($hostId <= 0) {
$error = 'Bitte einen Host wählen.';
} elseif ($commandId <= 0 && $rawCommand === '') {
$error = 'Bitte einen Befehl wählen oder einen Befehl eingeben.';
} else {
$selectedCommand = '';
if ($commandId > 0) {
foreach ($commands as $c) {
if ((int)$c['id'] === $commandId) {
if (!auth_is_admin() && !empty($c['admin_only'])) {
$error = 'Dieser Befehl ist nur für Admins.';
} else {
$selectedCommand = (string)$c['command'];
if (!empty($c['timeout_sec'])) {
$timeoutSec = (int)$c['timeout_sec'];
}
}
break;
}
}
$commandToRun = $presetCommand !== '' ? $presetCommand : $rawCommand;
if ($commandToRun !== '') {
$terminalUrl .= '&arg=' . rawurlencode(base64_encode($commandToRun));
}
if (!$error) {
$commandText = $selectedCommand !== '' ? $selectedCommand : $rawCommand;
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === 'pgsql') {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)
RETURNING id'
);
$stmt->execute([
'host_id' => $hostId,
'command_id' => $commandId > 0 ? $commandId : null,
'command_text' => $commandText,
'status' => 'queued',
'timeout_sec' => $timeoutSec,
'created_by' => auth_display_name() ?: null,
]);
$runId = (int)$stmt->fetchColumn();
} else {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)'
);
$stmt->execute([
'host_id' => $hostId,
'command_id' => $commandId > 0 ? $commandId : null,
'command_text' => $commandText,
'status' => 'queued',
'timeout_sec' => $timeoutSec,
'created_by' => auth_display_name() ?: null,
]);
$runId = (int)$pdo->lastInsertId();
}
try {
$redis = module_fn('pi_control', 'redis');
$payload = json_encode(['run_id' => $runId], JSON_THROW_ON_ERROR);
$redis->command(['RPUSH', $queueName, $payload]);
$notice = 'Befehl wurde in die Queue gestellt.';
} catch (\Throwable $e) {
$pdo->exec('UPDATE ' . $table('runs') . ' SET status = \'queue_error\' WHERE id = ' . (int)$runId);
$notice = 'Befehl gespeichert, aber Queue nicht erreichbar.';
foreach ($hosts as $h) {
if ((int)$h['id'] === $hostId) {
$terminalHostLabel = (string)($h['name'] ?? $h['host']);
break;
}
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => $terminalError === null,
'error' => $terminalError,
'url' => $terminalUrl,
'token' => $terminalToken,
'host' => $terminalHostLabel,
]);
exit;
}
if (isset($_GET['run_command_json'])) {
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
$commandId = (int)($_POST['terminal_preset_id'] ?? 0);
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
$timeoutSec = $defaultTimeout;
$error = null;
$notice = null;
if ($hostId <= 0) {
$error = 'Bitte einen Host wählen.';
} elseif ($commandId <= 0 && $rawCommand === '') {
$error = 'Bitte einen Befehl wählen oder einen Befehl eingeben.';
} else {
$selectedCommand = '';
if ($commandId > 0) {
foreach ($commands as $c) {
if ((int)$c['id'] === $commandId) {
if (!auth_is_admin() && !empty($c['admin_only'])) {
$error = 'Dieser Befehl ist nur für Admins.';
} else {
$selectedCommand = (string)$c['command'];
if (!empty($c['timeout_sec'])) {
$timeoutSec = (int)$c['timeout_sec'];
}
}
break;
}
}
}
if (!$error) {
$commandText = $selectedCommand !== '' ? $selectedCommand : $rawCommand;
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === 'pgsql') {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)
RETURNING id'
);
$stmt->execute([
'host_id' => $hostId,
'command_id' => $commandId > 0 ? $commandId : null,
'command_text' => $commandText,
'status' => 'queued',
'timeout_sec' => $timeoutSec,
'created_by' => auth_display_name() ?: null,
]);
$runId = (int)$stmt->fetchColumn();
} else {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)'
);
$stmt->execute([
'host_id' => $hostId,
'command_id' => $commandId > 0 ? $commandId : null,
'command_text' => $commandText,
'status' => 'queued',
'timeout_sec' => $timeoutSec,
'created_by' => auth_display_name() ?: null,
]);
$runId = (int)$pdo->lastInsertId();
}
try {
$redis = module_fn('pi_control', 'redis');
$payload = json_encode(['run_id' => $runId], JSON_THROW_ON_ERROR);
$redis->command(['RPUSH', $queueName, $payload]);
$notice = 'Befehl wurde in die Queue gestellt.';
} catch (\Throwable $e) {
$pdo->exec('UPDATE ' . $table('runs') . ' SET status = \'queue_error\' WHERE id = ' . (int)$runId);
$notice = 'Befehl gespeichert, aber Queue nicht erreichbar.';
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => $error === null,
'error' => $error,
'notice' => $notice,
]);
exit;
}
// Form submits are handled via AJAX to avoid reloads.
$runs = $pdo->query(
'SELECT r.*, h.name AS host_name, h.host AS host_addr
FROM ' . $table('runs') . ' r
@@ -155,17 +248,9 @@ $runs = $pdo->query(
<div class="grid" style="margin-top:1rem;">
<div class="card form-card" style="background:var(--panel-2);">
<strong>Live-Konsole</strong>
<?php if ($terminalError): ?>
<div class="card" style="margin-top:1rem; border-color:#ffb4a8; background:#fff5f3; color:#7a2114;">
<?= e($terminalError) ?>
</div>
<?php elseif ($terminalNotice): ?>
<div class="card" style="margin-top:1rem; border-color:var(--accent-2);">
<?= e($terminalNotice) ?>
</div>
<?php endif; ?>
<form method="post" class="form-grid" style="margin-top:.75rem;">
<input type="hidden" name="action" value="open_console">
<div class="card" style="margin-top:1rem; border-color:#ffb4a8; background:#fff5f3; color:#7a2114; display:none;" data-console-error></div>
<div class="card" style="margin-top:1rem; border-color:var(--accent-2); display:none;" data-console-notice></div>
<form method="post" class="form-grid" style="margin-top:.75rem;" data-console-form>
<label class="form-field">
<span class="muted">Host</span>
<select name="terminal_host_id" required title="Pi auswählen, zu dem die Konsole verbindet.">
@@ -176,47 +261,9 @@ $runs = $pdo->query(
</select>
</label>
<label class="form-field">
<span class="muted">Konsole</span>
<input type="text" value="ttyd" disabled>
</label>
<button class="cta-button" type="submit">Konsole öffnen</button>
</form>
<?php if ($terminalUrl): ?>
<div class="card" style="margin-top:1rem;">
<div style="display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;">
<strong>Aktive Konsole</strong>
<a class="nav-link" href="<?= e($terminalUrl) ?>" target="_blank" rel="noopener">In neuem Tab öffnen</a>
</div>
<?php if ($terminalToken): ?>
<div class="muted" style="margin-top:.5rem;">
Token: <code><?= e($terminalToken) ?></code>
</div>
<?php endif; ?>
<div style="margin-top:.75rem; border-radius:12px; overflow:hidden; border:1px solid var(--line); background:#0b0f17;">
<iframe src="<?= e($terminalUrl) ?>" title="Pi Konsole" style="width:100%; height:520px; border:0;"></iframe>
</div>
</div>
<?php endif; ?>
</div>
<div class="card form-card" style="background:var(--panel-2);">
<strong>Befehl ausführen</strong>
<form method="post" class="form-grid" style="margin-top:.75rem;">
<input type="hidden" name="action" value="run_command">
<label class="form-field">
<span class="muted">Host</span>
<select name="host_id" required>
<option value="">Host wählen</option>
<?php foreach ($hosts as $h): ?>
<option value="<?= e((string)$h['id']) ?>"><?= e($h['name'] ?? $h['host']) ?></option>
<?php endforeach; ?>
</select>
</label>
<label class="form-field">
<span class="muted">Preset</span>
<select name="command_id">
<option value="">Preset auswählen (optional)</option>
<span class="muted">Vorlage</span>
<select name="terminal_preset_id" title="Optional: Vorlage direkt in der Konsole ausführen.">
<option value="">Vorlage auswählen (optional)</option>
<?php foreach ($commands as $c): ?>
<?php if (!auth_is_admin() && !empty($c['admin_only'])) { continue; } ?>
<option value="<?= e((string)$c['id']) ?>"><?= e($c['label'] ?? '') ?></option>
@@ -225,15 +272,42 @@ $runs = $pdo->query(
</label>
<label class="form-field">
<span class="muted">Direkter Command</span>
<textarea name="command_text" rows="3" placeholder="Oder Command direkt eingeben"></textarea>
<textarea name="terminal_command_text" rows="2" placeholder="Optional: Command direkt ausführen"></textarea>
</label>
<button class="cta-button" type="submit">Befehl senden</button>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="cta-button" type="button" data-open-console>Konsole öffnen</button>
<button class="nav-link" type="button" data-run-command>Im Hintergrund ausführen</button>
</div>
</form>
<p class="muted" style="margin-top:.5rem;">Befehle werden über die Queue ausgeführt.</p>
<div class="muted" style="margin-top:.5rem;">
Token: <code data-console-token></code>
</div>
<?php if ($terminalUrl): ?>
<div class="console-launch"
data-url="<?= e($terminalUrl) ?>"
data-host="<?= e($terminalHostLabel ?: 'Konsole') ?>"
data-token="<?= e($terminalToken ?: '') ?>"></div>
<?php endif; ?>
</div>
<div class="card form-card" style="background:var(--panel-2);">
<strong>Letzte Runs</strong>
<strong>Konsole Tabs</strong>
<div class="console-tabs" data-console-tabs>
<div class="console-tab-bar" data-console-tab-bar></div>
<div class="console-tab-panels" data-console-tab-panels></div>
</div>
<p class="muted" style="margin-top:.5rem;">Mehrere Konsolen bleiben hier parallel offen.</p>
</div>
<div class="card form-card" style="background:var(--panel-2);">
<div style="display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;">
<strong>Queue</strong>
<div class="muted" style="display:flex; align-items:center; gap:10px;">
<span>Update in <span data-queue-countdown>10</span>s</span>
<button class="icon-button" type="button" data-queue-refresh title="Jetzt aktualisieren">↻</button>
</div>
</div>
<div style="margin-top:.75rem; overflow:auto;">
<table class="table" style="min-width:560px;">
<thead>
@@ -247,29 +321,8 @@ $runs = $pdo->query(
<th>Timeout</th>
</tr>
</thead>
<tbody>
<?php if (!$runs): ?>
<tr><td colspan="7" class="muted">Noch keine Runs.</td></tr>
<?php endif; ?>
<?php foreach ($runs as $r): ?>
<?php
$out = (string)($r['output'] ?? '');
$err = (string)($r['error'] ?? '');
$snippet = $out !== '' ? $out : $err;
if (strlen($snippet) > 140) {
$snippet = substr($snippet, 0, 140) . '…';
}
?>
<tr>
<td><?= e((string)$r['id']) ?></td>
<td><?= e($r['status'] ?? '') ?></td>
<td><?= e($r['host_name'] ?? $r['host_addr'] ?? '') ?></td>
<td class="muted" style="max-width:360px;"><code><?= e($r['command_text'] ?? '') ?></code></td>
<td><?= e($r['created_by'] ?? '') ?></td>
<td class="muted" style="max-width:240px;"><code><?= e($snippet) ?></code></td>
<td><?= !empty($r['timeout_sec']) ? e((string)$r['timeout_sec']) . 's' : 'default' ?></td>
</tr>
<?php endforeach; ?>
<tbody data-queue-body>
<?= $renderRuns($runs) ?>
</tbody>
</table>
</div>