Repositories | Polyback | Log in to see private repositories
14,681 bytes | parent directory
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
// Deploy Updates: where each program's code comes from, building it on this server, and putting a
// finished build live. This page only records requests; see the Deploy class for who does the work.
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Deploy;
use pizzaboxer\ProjectPolygon\System;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\PageBuilder;
Users::RequireAdmin(Users::STAFF_ADMINISTRATOR);
function e($text) { return htmlspecialchars((string)$text, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"); }
function csrf() { return '<input type="hidden" name="csrf" value="'.e(SESSION["csrfToken"]).'">'; }
function status_badge($status) { return '<span class="badge badge-'.(Deploy::STATUS_COLORS[$status] ?? "secondary").'">'.e(ucfirst($status)).'</span>'; }
function when($time)
{
return $time ? '<span title="'.date('j/n/Y g:i:s A', $time).' UTC">'.GetReadableTime($time).'</span>' : "-";
}
$error = false;
$notices = [
"source" => "The source was saved.",
"build" => "The build was requested: it starts as soon as the build runner is free.",
"cancel" => "The build is being cancelled.",
"deploy" => "The deploy was requested: it starts in a moment.",
"rollback" => "The rollback was requested: it starts in a moment."
];
$notice = $notices[$_GET["Done"] ?? ""] ?? false;
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$do = $_POST["do"] ?? "";
$program = $_POST["program"] ?? "";
$name = Deploy::ProgramExists($program) ? Deploy::PROGRAMS[$program]["Name"] : "";
if (!is_string($_POST["csrf"] ?? null) || !hash_equals((string)SESSION["csrfToken"], $_POST["csrf"]))
{
$error = "The form expired or didn't come from this site. Please try again.";
}
else if ($do === "build" && $program === "all")
{
$queued = [];
foreach (Deploy::PROGRAMS as $key => $info)
{
if ($id = Deploy::QueueBuild($key, SESSION["user"]["id"])) $queued[] = "{$info["Name"]} #{$id}";
}
if (!$queued) $error = "Every program is already being built.";
else Users::LogStaffAction("[ Deploy ] Requested builds: ".implode(", ", $queued));
}
else if (!$name)
{
$error = "That program doesn't exist.";
}
else if ($do === "source")
{
$url = trim((string)($_POST["url"] ?? ""));
$branch = trim((string)($_POST["branch"] ?? ""));
if (!Deploy::ValidGitURL($url)) $error = "The git URL has to be an https:// URL without a username or password.";
else if (!Deploy::ValidBranch($branch)) $error = "That isn't a valid branch name.";
else
{
Deploy::SaveSource($program, $url, $branch, SESSION["user"]["id"]);
Users::LogStaffAction("[ Deploy ] Set the source of $name to $url, branch $branch");
}
}
else if ($do === "build")
{
$id = Deploy::QueueBuild($program, SESSION["user"]["id"]);
if (!$id) $error = "$name is already being built.";
else Users::LogStaffAction("[ Deploy ] Requested build #$id of $name");
}
else if ($do === "cancel")
{
$id = (int)($_POST["build"] ?? 0);
Deploy::CancelBuild($id);
Users::LogStaffAction("[ Deploy ] Cancelled build #$id of $name");
}
else if ($do === "deploy" || $do === "rollback")
{
$id = (int)($_POST["build"] ?? 0);
$error = Deploy::QueueAction($program, $do, $id, SESSION["user"]["id"]) ?? false;
if (!$error) Users::LogStaffAction($do === "deploy" ? "[ Deploy ] Deployed build #$id of $name" : "[ Deploy ] Rolled $name back to the previous version");
}
else
{
$error = "Unknown action.";
}
if (!$error)
{
header("Location: /admin/deploy-updates?Done=$do");
die();
}
}
/* ---------- one log ---------- */
if (isset($_GET["Build"]) || isset($_GET["Action"]))
{
$isBuild = isset($_GET["Build"]);
$item = $isBuild ? Deploy::GetBuild($_GET["Build"]) : Deploy::GetAction($_GET["Action"]);
if (!$item) PageBuilder::instance()->errorCode(404);
$programName = Deploy::PROGRAMS[$item->Program]["Name"] ?? $item->Program;
$title = $isBuild ? "Build #{$item->ID} of $programName" : ($item->Action == "rollback" ? "Rollback" : "Deploy")." of $programName (build #{$item->BuildID})";
$pageBuilder = new PageBuilder(["title" => $title]);
$pageBuilder->buildHeader();
?>
<p class="mb-2"><a href="/admin/deploy-updates"><i class="far fa-arrow-left"></i> Deploy Updates</a></p>
<h3 class="font-weight-normal"><?=e($title)?> <small id="deploy-state"><?=status_badge($item->Status)?></small></h3>
<?php if ($isBuild && $item->CommitHash) { ?>
<p class="mb-1"><code><?=e($item->CommitHash)?></code> by <?=e($item->CommitAuthor)?>, <?=when($item->CommitTime)?></p>
<pre class="mb-2"><?=e($item->CommitMessage)?></pre>
<?php } if ($isBuild && ($artifacts = json_decode((string)$item->Artifacts, true))) { ?>
<table class="table table-sm">
<thead><tr><th class="font-weight-normal">Platform</th><th class="font-weight-normal">File</th><th class="font-weight-normal">Size</th><th class="font-weight-normal">SHA-256</th></tr></thead>
<tbody>
<?php foreach ($artifacts as $platform => $file) { ?>
<tr><td><?=e($platform)?></td><td><?=e($file["file"])?></td><td><?=System::GetFileSize($file["size"])?></td><td class="text-break"><small><code><?=e($file["sha256"])?></code></small></td></tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<pre id="deploy-log" class="border rounded p-2" style="max-height:70vh;overflow:auto;white-space:pre-wrap;font-size:80%"><?=e($item->Log ?: "Nothing yet.")?></pre>
<?php if (in_array($item->Status, ["queued", "running"])) { ?>
<script>
$(function()
{
var log = document.getElementById("deploy-log");
function load()
{
$.get("/api/admin/deploy-status", {<?=$isBuild ? "Build" : "Action"?>: <?=(int)$item->ID?>}, function(data)
{
var atEnd = log.scrollHeight - log.scrollTop - log.clientHeight < 40;
if (data.log) log.textContent = data.log;
if (atEnd) log.scrollTop = log.scrollHeight;
if (data.state != "queued" && data.state != "running") location.reload();
else setTimeout(load, 2000);
}, "json").fail(function() { setTimeout(load, 5000); }); // the site may be updating itself
}
log.scrollTop = log.scrollHeight;
load();
});
</script>
<?php }
$pageBuilder->buildFooter();
die();
}
/* ---------- overview ---------- */
$stopped = Deploy::StoppedDaemons();
$activity = Deploy::GetActivity();
$runningGames = (int)Database::singleton()->run("SELECT COUNT(*) FROM GameJobs WHERE Status IN ('Loading', 'Ready')")->fetchColumn();
$pageBuilder = new PageBuilder(["title" => "Deploy Updates"]);
$pageBuilder->buildHeader();
?>
<div class="row">
<div class="col">
<h2 class="font-weight-normal">Deploy Updates</h2>
<p>Building fetches a program's branch and compiles it on this server; nothing changes for players until you deploy the finished build.</p>
</div>
<form method="post" class="col-auto">
<?=csrf()?><input type="hidden" name="do" value="build"><input type="hidden" name="program" value="all">
<button class="btn btn-primary"><i class="far fa-hammer"></i> Build all</button>
</form>
</div>
<?php if ($error) { ?><div class="alert alert-danger"><?=e($error)?></div><?php } ?>
<?php if ($notice) { ?><div class="alert alert-success"><?=e($notice)?></div><?php } ?>
<?php if (in_array("runner", $stopped)) { ?><div class="alert alert-danger">The build runner isn't running on the server: builds will wait until it is started (<code>/srv/polygon/start.sh</code>).</div><?php } ?>
<?php if (in_array("deployd", $stopped)) { ?><div class="alert alert-danger">The deploy daemon isn't running on the server: deploys will wait until it is started (<code>/srv/polygon/start.sh</code>).</div><?php } ?>
<?php foreach (Deploy::PROGRAMS as $program => $info) {
$source = Deploy::GetSource($program);
$state = Deploy::GetState($program);
$builds = Deploy::GetBuilds($program);
$actions = Deploy::GetActions($program);
$deploying = in_array($actions[0]->Status ?? "", ["queued", "running"]);
$building = (bool)array_filter($builds, fn($b) => in_array($b->Status, ["queued", "running"]));
$warning = $info["Warning"];
if ($program == "gameserver") $warning .= $runningGames ? " Games running now: $runningGames." : " No games are running now.";
?>
<div class="card mb-4" id="<?=$program?>">
<div class="card-header">
<div class="row">
<div class="col">
<h4 class="font-weight-normal mb-0"><i class="fal <?=$info["Icon"]?>"></i> <?=e($info["Name"])?></h4>
<small><?php if ($state) { ?>Live: <b><?=e($state->CurrentVersion)?></b> (build #<?=(int)$state->CurrentBuildID?>), deployed <?=when($state->Updated)?><?php } else { ?>Not deployed from this page yet<?php } ?></small>
</div>
<div class="col-auto">
<?php if ($state && $state->PreviousBuildID) { ?>
<form method="post" class="d-inline deploy-confirm" data-title="Roll back <?=e($info["Name"])?> to <?=e($state->PreviousVersion)?>?" data-warning="<?=e($warning)?>">
<?=csrf()?><input type="hidden" name="do" value="rollback"><input type="hidden" name="program" value="<?=$program?>">
<button class="btn btn-sm btn-outline-danger"<?=$deploying ? " disabled" : ""?>><i class="far fa-undo"></i> Roll back to <?=e($state->PreviousVersion)?></button>
</form>
<?php } ?>
<form method="post" class="d-inline">
<?=csrf()?><input type="hidden" name="do" value="build"><input type="hidden" name="program" value="<?=$program?>">
<button class="btn btn-sm btn-primary"<?=$building ? " disabled" : ""?>><i class="far fa-hammer"></i> Build</button>
</form>
</div>
</div>
</div>
<div class="card-body">
<form method="post" class="form-row mb-2">
<?=csrf()?><input type="hidden" name="do" value="source"><input type="hidden" name="program" value="<?=$program?>">
<div class="col-md-7 mb-2"><input class="form-control form-control-sm" type="text" name="url" maxlength="255" required value="<?=e($source->GitURL ?? "")?>" placeholder="https://" aria-label="Git URL" autocomplete="off" spellcheck="false"></div>
<div class="col-md-3 mb-2"><input class="form-control form-control-sm" type="text" name="branch" maxlength="100" required value="<?=e($source->Branch ?? "master")?>" aria-label="Branch" autocomplete="off" spellcheck="false"></div>
<div class="col-md-2 mb-2"><button class="btn btn-sm btn-outline-secondary btn-block">Save source</button></div>
</form>
<div class="alert alert-warning py-2"><i class="far fa-exclamation-triangle"></i> <b>When you deploy:</b> <?=e($warning)?></div>
<?php if ($builds) { ?>
<div class="table-responsive">
<table class="table table-sm table-hover mb-2">
<thead>
<tr>
<th class="font-weight-normal" scope="col">Build</th>
<th class="font-weight-normal" scope="col">Status</th>
<th class="font-weight-normal" scope="col">Commit</th>
<th class="font-weight-normal" scope="col">Output</th>
<th class="font-weight-normal" scope="col">Requested</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($builds as $build) { $artifacts = json_decode((string)$build->Artifacts, true) ?: []; $live = $state && $state->CurrentBuildID == $build->ID; ?>
<tr>
<td>#<?=(int)$build->ID?><br><small><?=e($build->Version)?></small></td>
<td><?=status_badge($build->Status)?><?=$live ? ' <span class="badge badge-primary">Live</span>' : ""?><br><small data-build-stage="<?=(int)$build->ID?>"><?=$build->Status == "running" ? e($build->Stage) : ($build->TimeFinished && $build->TimeStarted ? gmdate("i:s", max(0, $build->TimeFinished - $build->TimeStarted)) : "")?></small></td>
<td style="max-width:20rem"><?php if ($build->CommitHash) { ?><code title="<?=e($build->CommitHash)?>"><?=e(substr($build->CommitHash, 0, 8))?></code> <small><?=e($build->CommitAuthor)?>, <?=when($build->CommitTime)?></small><?php } ?><div class="text-truncate" title="<?=e($build->CommitMessage)?>"><small><?=e(strtok((string)$build->CommitMessage, "\n"))?></small></div></td>
<td><?php foreach ($artifacts as $platform => $file) { ?><small class="d-block text-nowrap" title="<?=e($file["file"])?>"><?=e($platform)?>: <?=System::GetFileSize($file["size"])?></small><?php } ?></td>
<td><small><?=when($build->TimeRequested)?><br><?=e($build->username)?></small></td>
<td class="text-right text-nowrap">
<a class="btn btn-sm btn-light" href="?Build=<?=(int)$build->ID?>">Log</a>
<?php if (in_array($build->Status, ["queued", "running"])) { ?>
<form method="post" class="d-inline">
<?=csrf()?><input type="hidden" name="do" value="cancel"><input type="hidden" name="program" value="<?=$program?>"><input type="hidden" name="build" value="<?=(int)$build->ID?>">
<button class="btn btn-sm btn-outline-danger"<?=$build->CancelRequested ? " disabled" : ""?>>Cancel</button>
</form>
<?php } else if ($build->Status == "success" && $artifacts) { ?>
<form method="post" class="d-inline deploy-confirm" data-title="Deploy <?=e($info["Name"])?> <?=e($build->Version)?>?" data-warning="<?=e($warning)?>">
<?=csrf()?><input type="hidden" name="do" value="deploy"><input type="hidden" name="program" value="<?=$program?>"><input type="hidden" name="build" value="<?=(int)$build->ID?>">
<button class="btn btn-sm btn-<?=$live ? "outline-" : ""?>success"<?=$deploying ? " disabled" : ""?>><?=$live ? "Deploy again" : "Deploy"?></button>
</form>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php } else { ?><p class="mb-2">No builds yet.</p><?php } ?>
<?php foreach ($actions as $action) { ?>
<small class="d-block"><?=status_badge($action->Status)?> <?=$action->Action == "rollback" ? "Rollback to" : "Deploy of"?> <?=e($action->Version)?> (build #<?=(int)$action->BuildID?>) by <?=e($action->username)?>, <?=when($action->TimeRequested)?> · <a href="?Action=<?=(int)$action->ID?>">Log</a></small>
<?php } ?>
</div>
</div>
<?php } ?>
<script>
$(function()
{
$(".deploy-confirm").on("submit", function() { return confirm($(this).data("title") + "\n\n" + $(this).data("warning")); });
// while something is waiting or running: show what it is doing, and load the page again when that changes
var fingerprint = <?=json_encode($activity["fingerprint"])?>;
function poll()
{
$.get("/api/admin/deploy-status", function(data)
{
if (data.fingerprint != fingerprint) return location.replace("/admin/deploy-updates");
$.each(data.stages, function(id, stage) { $("[data-build-stage=" + id + "]").text(stage || ""); });
if (data.active) setTimeout(poll, 3000);
}, "json").fail(function() { setTimeout(poll, 5000); }); // the site may be updating itself
}
<?php if ($activity["active"]) { ?>poll();<?php } ?>
});
</script>
<?php $pageBuilder->buildFooter(); ?>