Files
laysite/bin/update.php

576 lines
24 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env php
<?php
declare(strict_types=1);
final class LaySiteUpdater
{
private const UPDATESCRIPT_VERSION = '1.0.0';
private const HOST = 'https://git.laysense.com';
private const PROJECT = '/laysense/laysite';
private const MAP_PATH = self::PROJECT . '/raw/branch/main/updatescript_map.json';
private const RELEASES_PATH = '/api/v1/repos' . self::PROJECT . '/releases';
private const TAG = '/^v(\d+\.\d+\.\d+)$/D';
// These two releases shipped with 1.4.0 in VERSION. Identify their original files when updating old installations.
private const LEGACY_VERSIONS = [
'1.4.2' => [
'bin/update.sh' => 'a1cc96a5ecc3db3074563877dec07f0ebf8689e90e0e9aece838071df4793e26',
'bin/update.php' => 'b13d3e925b59589f4d599d6deebb1fb27fa81ad0b98e5d0c67199279c3de9635',
],
'1.4.1' => [
'public/assets/vendor/codemirror/xml.min.js' => 'c0c38a5cf20549c4e20d90428edd830cbbf6a631245a1ac2fb8e88676d4c0b7a',
],
];
private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f'];
private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|updatescript_map\.json|composer\.(?:json|lock)|start\.php)$/D';
private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
public function __construct(private readonly string $root)
{
}
public function execute(?string $target, ?string $backup): void
{
$current = $this->version();
$map = self::remoteJson(self::MAP_PATH, 65536, 10000);
$rule = is_object($map) ? ($map->{self::UPDATESCRIPT_VERSION} ?? null) : null;
if (!is_object($rule)) {
throw new RuntimeException('当前更新器未列入兼容表,请下载新版 update.php。');
}
$from = self::parseRange($rule->from ?? null);
$to = self::parseRange($rule->to ?? null);
$releases = self::releases();
$latest = array_key_first($releases);
$latestVersion = $latest === null ? null : substr($latest, 1);
if (!self::inRange($current, $from, $latestVersion)) {
throw new RuntimeException("当前站点 v$current 超出此更新器的起始版本范围 {$rule->from}。");
}
$eligible = array_filter($releases, static function (string $tag) use ($current, $to, $latestVersion): bool {
$version = substr($tag, 1);
return version_compare($version, $current, '>') && self::inRange($version, $to, $latestVersion);
}, ARRAY_FILTER_USE_KEY);
printf("更新器 v%s,当前站点 v%s\n兼容起始版本 %s,目标范围 %s\n",
self::UPDATESCRIPT_VERSION, $current, $rule->from, $rule->to);
if ($target === 'check') {
if ($latest !== null) {
printf("上游最新正式发布 %s\n", $latest);
}
echo $eligible === [] ? "暂无可升级的正式发布版本。\n"
: '可升级至 ' . implode('、', array_keys($eligible)) . PHP_EOL;
return;
}
if ($target === null) {
$target = self::chooseRelease($eligible);
if ($target === null) {
return;
}
} elseif ($target === 'v' . $current) {
printf("当前已安装 %s。\n", $target);
return;
}
if (!isset($eligible[$target])) {
throw new RuntimeException("无法从 v$current 升级到 {$target}。可选版本为 "
. ($eligible === [] ? '无。' : implode('、', array_keys($eligible)) . '。'));
}
$this->update($current, $target, $backup);
}
private static function parseRange(mixed $value): array
{
if (!is_string($value) || !preg_match('/^v(\d+\.\d+\.\d+)-(?:v(\d+\.\d+\.\d+)|latest)$/D', $value, $parts)
|| (isset($parts[2]) && version_compare($parts[1], $parts[2], '>'))) {
throw new RuntimeException('更新器兼容表中的版本范围无效。');
}
return [$parts[1], $parts[2] ?? null];
}
private static function inRange(string $version, array $range, ?string $latest): bool
{
[$minimum, $maximum] = $range;
$maximum ??= $latest;
return version_compare($version, $minimum, '>=') && ($maximum === null || version_compare($version, $maximum, '<='));
}
private static function releases(): array
{
$result = [];
$deadline = hrtime(true) + 10_000_000_000;
for ($page = 1; ; $page++) {
$timeout = (int) (($deadline - hrtime(true)) / 1_000_000);
if ($timeout <= 0) {
throw new RuntimeException('查询 LaySite 发布列表超时。');
}
$entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout);
if (!is_array($entries)) {
throw new RuntimeException('LaySite 发布列表格式无效。');
}
foreach ($entries as $entry) {
if (!is_string($entry->tag_name ?? null) || !is_bool($entry->draft ?? null) || !is_bool($entry->prerelease ?? null)) {
throw new RuntimeException('LaySite 发布列表格式无效。');
}
if (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) {
$result[$entry->tag_name] = $entry;
}
}
if (count($entries) < 50) {
break;
}
}
uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1)));
return $result;
}
private static function remoteJson(string $path, int $limit, int $timeout): mixed
{
$stream = fopen('php://temp', 'w+b');
if ($stream === false) {
throw new RuntimeException('无法创建更新查询缓冲区。');
}
try {
self::download($path, $stream, $limit, $timeout);
rewind($stream);
return json_decode((string) stream_get_contents($stream), flags: JSON_THROW_ON_ERROR);
} finally {
fclose($stream);
}
}
private static function chooseRelease(array $releases): ?string
{
if ($releases === []) {
echo "暂无可升级的正式发布版本。\n";
return null;
}
$tags = array_keys($releases);
foreach ($tags as $index => $tag) {
$release = $releases[$tag];
$title = self::terminalText($release->name ?? '');
$details = self::terminalText($release->body ?? '');
printf("\n%d. %s%s\n", $index + 1, $tag, $title === '' || $title === $tag ? '' : ' · ' . str_replace("\n", ' ', $title));
echo ' ' . str_replace("\n", "\n ", $details === '' ? '暂无发布说明。' : $details) . PHP_EOL;
}
while (true) {
echo "\n请选择版本编号或输入标签,回车取消\n> ";
$selection = trim((string) fgets(STDIN));
if ($selection === '' || strtolower($selection) === 'q') {
return null;
}
if (isset($releases[$selection])) {
return $selection;
}
if (ctype_digit($selection) && isset($tags[(int) $selection - 1])) {
return $tags[(int) $selection - 1];
}
echo "请输入列表中的编号或版本。\n";
}
}
private static function terminalText(mixed $value): string
{
if (!is_string($value)) {
return '';
}
return trim(preg_replace('/[^\P{C}\n\t]/u', '', str_replace(["\r\n", "\r"], "\n", $value)) ?? '');
}
private function update(string $current, string $target, ?string $backup): void
{
$runtime = $this->root . '/runtime';
self::makeDirectory($runtime);
$lock = fopen($runtime . '/release-update.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
throw new RuntimeException('无法取得 LaySite 更新锁。');
}
$pending = $runtime . '/release-update-pending';
$work = $this->root . '/.laysite-update-' . bin2hex(random_bytes(8));
try {
if (file_exists($pending) || is_link($pending)) {
throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending)));
}
if ($this->version() !== $current) {
throw new RuntimeException('站点版本已经变更,请重新选择更新目标。');
}
$backup = $this->backupPath($backup, $current, $target);
if (!mkdir($work, 0700)) {
throw new RuntimeException('无法建立更新暂存目录。');
}
$base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip');
// Accept the VERSION file already identified above, including the old release numbering.
$base['VERSION']['hash'] = hash_file('sha256', $this->root . '/VERSION');
$release = $this->archive($target, substr($target, 1), $work . '/release.zip');
$plan = $this->plan($base, $release, $backup);
$php = getenv('LAYSITE_PHP') ?: PHP_BINARY;
self::run([$php, 'bin/backup.php', 'export', $backup], $this->root);
$vendor = $this->stageDependencies($work, $plan, $release);
if ($plan !== $this->plan($base, $release, $backup)) {
throw new RuntimeException('准备更新期间,站点文件发生了变化。');
}
$this->apply($work, $pending, $plan, $release, $vendor, $php);
printf("已更新至 %s,可使用原站点配置启动 Webman。\n", $target);
} finally {
if (is_dir($work) && !is_file($pending)) {
self::removeDirectory($work);
}
fclose($lock);
}
}
private function backupPath(?string $path, string $current, string $target): string
{
if ($path === null) {
$directory = $this->root . '/storage/backups';
self::makeDirectory($directory);
$path = sprintf('%s/laysite-v%s-%s-%s-%s.tar', $directory, $current, $target, gmdate('Ymd-His'), bin2hex(random_bytes(4)));
} elseif (!str_starts_with($path, '/')) {
$path = $this->root . '/' . $path;
}
$directory = realpath(dirname($path));
if ($directory === false || !str_ends_with($path, '.tar') || file_exists($path) || is_link($path)) {
throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。');
}
$path = $directory . '/' . basename($path);
printf("站点备份将写入 %s\n", $path);
return $path;
}
private function version(): string
{
$version = trim((string) @file_get_contents($this->root . '/VERSION'));
if (!preg_match('/^\d+\.\d+\.\d+$/D', $version)) {
throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。');
}
if ($version === '1.4.0') {
foreach (self::LEGACY_VERSIONS as $tag => $files) {
foreach ($files as $path => $hash) {
if (@hash_file('sha256', $this->root . '/' . $path) === $hash) {
return $tag;
}
}
}
}
return $version;
}
private static function download(string $path, $stream, int $limit, int $timeout): void
{
$curl = curl_init(self::HOST . $path);
$bytes = 0;
curl_setopt_array($curl, [
CURLOPT_USERAGENT => 'LaySite release updater',
CURLOPT_CONNECTTIMEOUT_MS => min(3500, $timeout),
CURLOPT_TIMEOUT_MS => $timeout,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_WRITEFUNCTION => static function (CurlHandle $curl, string $chunk) use ($stream, $limit, &$bytes): int {
$bytes += strlen($chunk);
return $bytes > $limit ? 0 : (int) fwrite($stream, $chunk);
},
]);
if (curl_exec($curl) === false) {
throw new RuntimeException('下载 LaySite 发布文件失败。' . ($bytes > $limit ? '文件超过大小限制。' : curl_error($curl)));
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。");
}
}
private function archive(string $ref, string $version, string $path): array
{
$stream = fopen($path, 'xb');
if ($stream === false) {
throw new RuntimeException('无法写入发布 ZIP。');
}
try {
self::download(self::PROJECT . "/archive/$ref.zip", $stream, self::MAX_ARCHIVE_BYTES, 60_000);
} finally {
fclose($stream);
}
$archive = new PharData($path);
$files = [];
$size = 0;
$prefix = 'phar://' . $path . '/laysite/';
foreach (new RecursiveIteratorIterator($archive) as $entry) {
$uri = $entry->getPathname();
if (!str_starts_with($uri, $prefix)) {
throw new RuntimeException('发布 ZIP 的目录结构无效。');
}
$name = substr($uri, strlen($prefix));
if ($entry->isLink() || !$entry->isFile() || str_contains($name, '\\')
|| preg_match('~(?:^|/)\.{0,2}(?:/|$)|[\x00-\x1f\x7f]~', $name)) {
throw new RuntimeException('发布 ZIP 包含无效的文件路径。');
}
$size += $entry->getSize();
if ($size > self::MAX_EXPANDED_BYTES) {
throw new RuntimeException('发布 ZIP 解压后的大小超过限制。');
}
if (!preg_match(self::MANAGED, $name)) {
continue;
}
$hash = hash_file('sha256', $uri);
if ($hash === false || isset($files[$name])) {
throw new RuntimeException('发布 ZIP 文件损坏。');
}
$files[$name] = ['uri' => $uri, 'hash' => $hash, 'mode' => $entry->getPerms() & 0777];
}
foreach (['VERSION', 'start.php', 'bin/install.php', 'composer.json', 'composer.lock', 'resources/schema.sql'] as $required) {
if (!isset($files[$required])) {
throw new RuntimeException('发布 ZIP 缺少 ' . $required);
}
}
$embedded = trim((string) file_get_contents($files['VERSION']['uri']));
if ($embedded !== $version) {
if ($embedded !== '1.4.0' || !isset(self::LEGACY_VERSIONS[$version])) {
throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。');
}
$canonical = $path . '.version';
$contents = $version . "\n";
if (file_put_contents($canonical, $contents) !== strlen($contents)) {
throw new RuntimeException('无法暂存发布版本号。');
}
$files['VERSION'] = ['uri' => $canonical, 'hash' => hash('sha256', $contents), 'mode' => 0644];
}
return $files;
}
private function plan(array $base, array $release, string $backup): array
{
clearstatcache();
require_once $this->root . '/vendor/autoload.php';
$database = App\Content\Database::path();
$media = App\Content\Media::directory();
$protected = array_unique([
$database, realpath($database) ?: $database, $media, realpath($media) ?: $media, $backup,
]);
$plan = [];
$conflicts = [];
foreach (array_keys($base + $release) as $name) {
$old = $base[$name]['hash'] ?? null;
$next = $release[$name]['hash'] ?? null;
if ($old === $next) {
continue;
}
try {
$path = $this->managedPath($name);
foreach ($protected as $reserved) {
if ($path === $reserved || str_starts_with($path, rtrim($reserved, '/') . '/')
|| str_starts_with($reserved, $path . '/') || in_array($path, [$database . '.key', $database . '-wal', $database . '-shm'], true)) {
throw new RuntimeException('更新路径与站点数据重叠。');
}
}
$local = is_file($path) ? hash_file('sha256', $path) : null;
if ($local === $next) {
continue;
}
if ($local !== $old) {
$conflicts[] = $name;
continue;
}
$plan[] = $name;
} catch (RuntimeException) {
$conflicts[] = $name;
}
}
if ($conflicts !== []) {
sort($conflicts);
throw new RuntimeException("以下路径与站点定制或数据冲突,尚未替换任何文件:\n" . implode("\n", $conflicts));
}
if (array_intersect(['composer.json', 'composer.lock'], $plan)) {
$vendor = $this->root . '/vendor';
foreach ($protected as $reserved) {
if ($reserved === $vendor || str_starts_with($reserved, $vendor . '/')) {
throw new RuntimeException('站点数据或备份路径位于 vendor 目录,请先调整该路径。');
}
}
}
return $plan;
}
private function managedPath(string $name): string
{
$path = $this->root;
$parts = explode('/', $name);
$leaf = array_pop($parts);
foreach ($parts as $part) {
$path .= '/' . $part;
if (is_link($path) || (file_exists($path) && !is_dir($path))) {
throw new RuntimeException('更新路径不可写:' . $name);
}
}
$path .= '/' . $leaf;
if (is_link($path) || (file_exists($path) && !is_file($path))) {
throw new RuntimeException('更新路径不可写:' . $name);
}
return $path;
}
private function stageDependencies(string $work, array $plan, array $release): ?string
{
if (!array_intersect(['composer.json', 'composer.lock'], $plan)) {
return null;
}
$dependencies = $work . '/dependencies';
self::makeDirectory($dependencies);
foreach (['composer.json', 'composer.lock'] as $name) {
$source = in_array($name, $plan, true) ? $release[$name]['uri'] : $this->root . '/' . $name;
if (!copy($source, $dependencies . '/' . $name)) {
throw new RuntimeException('无法准备 Composer 依赖。');
}
}
$vendor = $dependencies . '/vendor';
self::run([
getenv('LAYSITE_COMPOSER') ?: 'composer', 'install', '--no-dev', '--prefer-dist',
'--no-interaction', '--no-scripts', '--no-plugins',
], $dependencies, array_replace(getenv(), ['COMPOSER' => 'composer.json', 'COMPOSER_VENDOR_DIR' => $vendor]));
if (!is_file($vendor . '/autoload.php')) {
throw new RuntimeException('Composer 没有在暂存目录生成依赖。');
}
return $vendor;
}
private function apply(string $work, string $pending, array $plan, array $release, ?string $vendor, string $php): void
{
$staged = [];
foreach ($plan as $name) {
$staged[$name] = null;
if (isset($release[$name])) {
$file = $work . '/files/' . $name;
self::makeDirectory(dirname($file));
$mode = $release[$name]['mode'] & 0755;
if ($name === 'bin/update.sh') {
$mode |= 0100;
}
if (!copy($release[$name]['uri'], $file) || !chmod($file, $mode ?: 0644)) {
throw new RuntimeException('无法暂存文件 ' . $name);
}
$staged[$name] = $file;
}
}
if ($vendor !== null) {
if (is_link($this->root . '/vendor') || !is_dir($this->root . '/vendor')) {
throw new RuntimeException('站点的 vendor 目录需要手动更新。');
}
$staged['vendor'] = $vendor;
}
$marker = fopen($pending, 'x');
if ($marker === false) {
throw new RuntimeException('无法写入更新记录。');
}
$record = $work . PHP_EOL;
$written = fwrite($marker, $record);
fclose($marker);
if ($written !== strlen($record)) {
unlink($pending);
throw new RuntimeException('无法写入完整的更新记录。');
}
$applied = [];
try {
foreach ($staged as $name => $source) {
$destination = $this->root . '/' . $name;
$previous = $work . '/previous/' . $name;
if (file_exists($destination)) {
self::makeDirectory(dirname($previous));
self::move($destination, $previous);
}
$applied[] = $name;
if ($source !== null) {
self::makeDirectory(dirname($destination));
self::move($source, $destination);
}
}
self::run([$php, 'bin/install.php'], $this->root);
} catch (Throwable $error) {
try {
foreach (array_reverse($applied) as $name) {
$path = $this->root . '/' . $name;
if (file_exists($path)) {
$discard = $work . '/discard/' . $name;
self::makeDirectory(dirname($discard));
self::move($path, $discard);
}
$previous = $work . '/previous/' . $name;
if (file_exists($previous)) {
self::move($previous, $path);
}
}
unlink($pending);
} catch (Throwable $rollback) {
throw new RuntimeException('更新回退未完成。原文件保存在 ' . $work . '。' . $rollback->getMessage(), previous: $error);
}
throw new RuntimeException('更新失败,原程序文件已恢复。' . $error->getMessage(), previous: $error);
}
unlink($pending);
}
private static function move(string $from, string $to): void
{
if (!rename($from, $to)) {
throw new RuntimeException('无法移动 ' . $from . ' 到 ' . $to);
}
}
private static function run(array $command, string $directory, ?array $environment = null): void
{
$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $directory, $environment);
if (!is_resource($process) || proc_close($process) !== 0) {
throw new RuntimeException('命令执行失败:' . implode(' ', array_slice($command, 0, 2)));
}
}
private static function makeDirectory(string $path): void
{
if (!is_dir($path) && !mkdir($path, 0755, true) && !is_dir($path)) {
throw new RuntimeException('无法建立目录 ' . $path);
}
}
private static function removeDirectory(string $path): void
{
$entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST);
foreach ($entries as $entry) {
if ($entry->isDir() && !$entry->isLink()) {
rmdir($entry->getPathname());
} else {
unlink($entry->getPathname());
}
}
rmdir($path);
}
}
$target = $argv[1] ?? null;
$backup = $argv[2] ?? null;
if ($argc > 3 || ($target === 'check' && $backup !== null)
|| ($target !== null && $target !== 'check' && !preg_match('/^v\d+\.\d+\.\d+$/D', $target))) {
fwrite(STDERR, "用法:php bin/update.php [check | vX.Y.Z [备份路径.tar]]\n");
exit(2);
}
umask(0027);
try {
(new LaySiteUpdater(getcwd()))->execute($target, $backup);
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
exit(1);
}