Repositories | Polyback | Log in to see private repositories


polyback-website / 95e5150e67c9f9be1d23113dda4841462e1440a7 / api/private/classes/pizzaboxer/ProjectPolygon/Deploy.php

7,901 bytes | parent directory

<?php

namespace pizzaboxer\ProjectPolygon;

use pizzaboxer\ProjectPolygon\Database;

// Deploy Updates (/admin/deploy-updates). The site only writes requests to the database; building
// is done by container/deploy/build-runner.py (unprivileged) and deploying by
// container/deploy/deployd.py (root), which check everything again.
class Deploy
{
	const PROGRAMS =
	[
		"website" =>
		[
			"Name" => "Website",
			"Icon" => "fa-globe",
			"Warning" => "The website may be unreachable for a few minutes while it's updated. New database schema changes are applied too, and they stay if you roll back."
		],
		"engine" =>
		[
			"Name" => "Engine",
			"Icon" => "fa-cube",
			"Warning" => "New games start on the new version. Running games keep theirs, and players can only join them with that version. Players' clients update on their next launch."
		],
		"gameserver" =>
		[
			"Name" => "Game server manager",
			"Icon" => "fa-server",
			"Warning" => "Restarting the manager empties the join queue (waiting players have to press Play again) and no new games can start for a few seconds. Running games keep running and the new manager takes them over, except games started by a manager from before this page existed: those end."
		],
		"bootstrapper" =>
		[
			"Name" => "Polyback Player",
			"Icon" => "fa-download",
			"Warning" => "Installed Polyback Players update themselves on their next launch, and the download page gives out the new version."
		]
	];

	const STATUS_COLORS = ["queued" => "secondary", "running" => "info", "success" => "success", "failed" => "danger", "cancelled" => "secondary"];

	static function ProgramExists($program)
	{
		return is_string($program) && isset(self::PROGRAMS[$program]);
	}

	// https only: no file paths, other protocols, usernames, passwords or options
	static function ValidGitURL($url)
	{
		return is_string($url) && strlen($url) <= 255 && !str_contains($url, "..")
			&& preg_match('#^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?/[A-Za-z0-9._~/%+-]*$#D', $url);
	}

	static function ValidBranch($branch)
	{
		return is_string($branch) && preg_match('#^[A-Za-z0-9._][A-Za-z0-9._/-]{0,99}$#D', $branch)
			&& !str_contains($branch, "..") && !str_contains($branch, "//") && !str_ends_with($branch, "/") && !str_ends_with($branch, ".lock");
	}

	static function GetSource($program)
	{
		return Database::singleton()->run("SELECT * FROM DeploySources WHERE Program = :program", [":program" => $program])->fetch(\PDO::FETCH_OBJ);
	}

	static function SaveSource($program, $url, $branch, $userId)
	{
		Database::singleton()->run(
			"INSERT INTO DeploySources (Program, GitURL, Branch, UpdatedBy, Updated) VALUES (:program, :url, :branch, :uid, UNIX_TIMESTAMP())
			ON DUPLICATE KEY UPDATE GitURL = VALUES(GitURL), Branch = VALUES(Branch), UpdatedBy = VALUES(UpdatedBy), Updated = VALUES(Updated)",
			[":program" => $program, ":url" => $url, ":branch" => $branch, ":uid" => $userId]
		);
	}

	// Returns the new build's ID, or null when one is already waiting or running
	static function QueueBuild($program, $userId)
	{
		$query = Database::singleton()->run(
			"INSERT INTO DeployBuilds (Program, RequestedBy, TimeRequested, GitURL, Branch)
			SELECT Program, :uid, UNIX_TIMESTAMP(), GitURL, Branch FROM DeploySources WHERE Program = :program
			AND NOT EXISTS (SELECT 1 FROM DeployBuilds AS b WHERE b.Program = :program2 AND b.Status IN ('queued', 'running'))",
			[":uid" => $userId, ":program" => $program, ":program2" => $program]
		);
		return $query->rowCount() ? Database::singleton()->lastInsertId() : null;
	}

	static function GetBuild($id)
	{
		return Database::singleton()->run("SELECT * FROM DeployBuilds WHERE ID = :id", [":id" => (int)$id])->fetch(\PDO::FETCH_OBJ);
	}

	static function GetAction($id)
	{
		return Database::singleton()->run("SELECT * FROM DeployActions WHERE ID = :id", [":id" => (int)$id])->fetch(\PDO::FETCH_OBJ);
	}

	static function CancelBuild($id)
	{
		Database::singleton()->run("UPDATE DeployBuilds SET Status = 'cancelled', TimeFinished = UNIX_TIMESTAMP() WHERE ID = :id AND Status = 'queued'", [":id" => (int)$id]);
		Database::singleton()->run("UPDATE DeployBuilds SET CancelRequested = 1 WHERE ID = :id AND Status = 'running'", [":id" => (int)$id]);
	}

	// $action: "deploy" (a finished build) or "rollback". Returns null, or why not.
	static function QueueAction($program, $action, $buildId, $userId)
	{
		if ($action === "deploy")
		{
			$build = self::GetBuild($buildId);
			if (!$build || $build->Program !== $program) return "That build doesn't exist.";
			if ($build->Status !== "success" || empty($build->Artifacts)) return "That build can't be deployed.";
		}
		else
		{
			$state = self::GetState($program);
			if (!$state || !$state->PreviousBuildID) return "There is no previous version to roll back to.";
			$buildId = $state->PreviousBuildID;
		}

		$query = Database::singleton()->run(
			"INSERT INTO DeployActions (Program, Action, BuildID, RequestedBy, TimeRequested)
			SELECT :program, :action, :build, :uid, UNIX_TIMESTAMP() FROM DUAL
			WHERE NOT EXISTS (SELECT 1 FROM DeployActions AS a WHERE a.Program = :program2 AND a.Status IN ('queued', 'running'))",
			[":program" => $program, ":action" => $action, ":build" => (int)$buildId, ":uid" => $userId, ":program2" => $program]
		);
		return $query->rowCount() ? null : "A deploy of this program is already waiting or running.";
	}

	static function GetState($program)
	{
		return Database::singleton()->run("SELECT * FROM DeployState WHERE Program = :program", [":program" => $program])->fetch(\PDO::FETCH_OBJ);
	}

	static function GetBuilds($program, $limit = 6)
	{
		return Database::singleton()->run(
			"SELECT b.ID, b.Program, b.Status, b.Stage, b.CancelRequested, b.TimeRequested, b.TimeStarted, b.TimeFinished, b.GitURL, b.Branch, b.CommitHash, b.CommitAuthor,
			b.CommitMessage, b.CommitTime, b.Version, b.Artifacts, b.ArtifactBytes, users.username FROM DeployBuilds AS b
			LEFT JOIN users ON users.id = b.RequestedBy WHERE b.Program = :program ORDER BY b.ID DESC LIMIT " . (int)$limit,
			[":program" => $program]
		)->fetchAll(\PDO::FETCH_OBJ);
	}

	static function GetActions($program, $limit = 3)
	{
		return Database::singleton()->run(
			"SELECT a.ID, a.Program, a.Action, a.BuildID, a.Status, a.TimeRequested, a.TimeStarted, a.TimeFinished, b.Version, users.username FROM DeployActions AS a
			LEFT JOIN DeployBuilds AS b ON b.ID = a.BuildID LEFT JOIN users ON users.id = a.RequestedBy
			WHERE a.Program = :program ORDER BY a.ID DESC LIMIT " . (int)$limit,
			[":program" => $program]
		)->fetchAll(\PDO::FETCH_OBJ);
	}

	// Daemons that haven't been heard from lately ("runner" builds, "deployd" deploys; a deploy
	// can keep deployd quiet for a while)
	static function StoppedDaemons()
	{
		$alive = Database::singleton()->run(
			"SELECT Name FROM DeployDaemons WHERE Heartbeat > UNIX_TIMESTAMP() - IF(Info = 'idle', 60, 900)"
		)->fetchAll(\PDO::FETCH_COLUMN);
		return array_diff(["runner", "deployd"], $alive);
	}

	// What the page shows live: the state of everything waiting or running, and a fingerprint
	// that changes when the page should be loaded again
	static function GetActivity()
	{
		$stages = Database::singleton()->run("SELECT ID, Stage FROM DeployBuilds WHERE Status = 'running'")->fetchAll(\PDO::FETCH_KEY_PAIR);
		$active = Database::singleton()->run(
			"SELECT (SELECT COUNT(*) FROM DeployBuilds WHERE Status IN ('queued', 'running')) + (SELECT COUNT(*) FROM DeployActions WHERE Status IN ('queued', 'running'))"
		)->fetchColumn();
		$fingerprint = Database::singleton()->run(
			"SELECT CONCAT_WS('-', (SELECT GROUP_CONCAT(ID, Status ORDER BY ID DESC LIMIT 20) FROM DeployBuilds), (SELECT GROUP_CONCAT(ID, Status ORDER BY ID DESC LIMIT 20) FROM DeployActions))"
		)->fetchColumn();
		return ["active" => (int)$active, "stages" => (object)$stages, "fingerprint" => md5((string)$fingerprint)];
	}
}