Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 11m34s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 12m8s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 15m14s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 15m47s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 13m48s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 14m15s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 16m38s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 17m2s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 1m16s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m53s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
223 lines
9.2 KiB
PHP
223 lines
9.2 KiB
PHP
<?php
|
||
|
||
namespace App\Support\Update;
|
||
|
||
use App\Support\Audit;
|
||
use App\Support\License\ServerError;
|
||
use App\Support\License\ServerMessages;
|
||
use Illuminate\Support\Facades\Artisan;
|
||
use Illuminate\Support\Facades\Log;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
/**
|
||
* Self-Updater: holt den Stand des aktiven Kanals als ZIP, legt ihn über die
|
||
* Produktion (mit geschützten Pfaden), migriert, leert Caches und merkt sich
|
||
* den neuen Commit-SHA. Ablauf und Prozentwerte nach docs/specs/self-updater.md.
|
||
*
|
||
* In zwei Schritten: installUpdate() tauscht die Dateien aus und endet. Migrationen
|
||
* laufen erst in der nächsten Anfrage (finishPending()) – mit dem neuen Code. In der
|
||
* Anfrage, die die Dateien austauscht, sind noch die alten Klassen geladen; neue
|
||
* Migrationen, die neue Klassen oder geänderte Modelle brauchen, liefen sonst mit
|
||
* dem alten Stand. Den zweiten Schritt löst die nächste Anfrage aus, die nach dem
|
||
* Austausch begonnen hat (EnsureNotInMaintenance) – meist die Fortschrittsabfrage.
|
||
*/
|
||
class Updater
|
||
{
|
||
public function __construct(
|
||
private readonly Channels $channels,
|
||
private readonly InstalledVersion $version,
|
||
private readonly UpdateProgress $progress,
|
||
private readonly MaintenanceFlag $maintenance,
|
||
private readonly ZipExtractor $extractor,
|
||
private readonly Migrations $migrations,
|
||
private readonly ?string $basePath = null,
|
||
) {}
|
||
|
||
/**
|
||
* Schritt 1: herunterladen, prüfen, Dateien austauschen. Der Wartungsmodus bleibt
|
||
* an, bis finishPending() die Datenbank aktualisiert hat.
|
||
*
|
||
* @return array{sha: string, files: int, pending: bool}
|
||
*/
|
||
public function installUpdate(?int $userId = null, ?string $channel = null): array
|
||
{
|
||
$channel ??= $this->channels->active();
|
||
$zipFile = storage_path('app/update-'.bin2hex(random_bytes(4)).'.zip');
|
||
$staging = storage_path('.update-staging');
|
||
$targetSha = null;
|
||
|
||
try {
|
||
$this->progress->set(0, 'maintenance', 'Wartungsmodus wird aktiviert …');
|
||
$this->maintenance->activate((int) config('updater.maintenance_max_seconds', 600));
|
||
|
||
$this->progress->set(5, 'version', 'Neueste Version wird ermittelt …');
|
||
$client = $this->channels->client($channel);
|
||
$targetSha = (string) ($client->version()['sha'] ?? '');
|
||
|
||
if (! InstalledVersion::isSha($targetSha)) {
|
||
throw new RuntimeException('Der Update-Server hat keinen gültigen Versionsstand gemeldet.');
|
||
}
|
||
|
||
$this->progress->set(20, 'download', 'Neue Version wird heruntergeladen …');
|
||
$headers = $client->downloadZip($targetSha, $zipFile);
|
||
$this->verifyZip($zipFile, $headers);
|
||
|
||
$this->progress->set(50, 'extract', 'Archiv wird entpackt …');
|
||
$this->extractor->extract($zipFile, $staging);
|
||
|
||
$this->progress->set(65, 'apply', 'Dateien werden übernommen …');
|
||
$result = (new StagingApplier(ProtectedPaths::fromConfig()))->apply($staging, $this->basePath ?? base_path());
|
||
|
||
// Bytecode-Cache verwerfen, bevor Schritt 2 freigegeben wird – sonst liefe er mit altem Code
|
||
$this->progress->set(70, 'cache', 'Zwischenspeicher werden geleert …');
|
||
$this->clearCaches();
|
||
$this->version->save($targetSha);
|
||
|
||
AtomicFile::write(self::pendingPath(), json_encode([
|
||
'channel' => $channel,
|
||
'sha' => $targetSha,
|
||
'files' => $result['copied'],
|
||
'user_id' => $userId,
|
||
'ready_at' => microtime(true),
|
||
]));
|
||
$this->progress->set(75, 'finalize', 'Dateien übernommen – die Datenbank wird mit der neuen Version aktualisiert …');
|
||
|
||
return ['sha' => $targetSha, 'files' => $result['copied'], 'pending' => true];
|
||
} catch (Throwable $e) {
|
||
$message = $e instanceof ServerError ? ServerMessages::for($e) : $e->getMessage();
|
||
|
||
$this->progress->fail($message);
|
||
Log::error('Update fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]);
|
||
Audit::log('update.failed', [
|
||
'channel' => $channel,
|
||
'sha' => $targetSha,
|
||
'migrations' => 0,
|
||
'error' => $message,
|
||
'code' => $e instanceof ServerError ? $e->errorCode : null,
|
||
], $userId);
|
||
|
||
// Sind die Dateien schon getauscht, holt RunPendingMigrations die Datenbank nach
|
||
$this->maintenance->deactivate();
|
||
|
||
throw $e;
|
||
} finally {
|
||
@unlink($zipFile);
|
||
Filesystem::deleteDirectory($staging);
|
||
}
|
||
}
|
||
|
||
public static function pendingPath(): string
|
||
{
|
||
return storage_path('.update-pending');
|
||
}
|
||
|
||
/**
|
||
* Schritt 2: Migrationen und Caches mit dem neuen Code, danach Wartungsmodus aus.
|
||
* Nur in einer Anfrage, die nach dem Dateiaustausch begonnen hat – eine ältere hat
|
||
* womöglich schon alte Klassen geladen. Gibt null zurück, wenn nichts zu tun ist.
|
||
*
|
||
* @return array{sha: string, migrations: int, files: int}|null
|
||
*/
|
||
public function finishPending(?float $requestStartedAt = null): ?array
|
||
{
|
||
$pending = json_decode((string) @file_get_contents(self::pendingPath()), true);
|
||
|
||
if (! is_array($pending) || ! isset($pending['ready_at'])) {
|
||
return null;
|
||
}
|
||
|
||
$requestStartedAt ??= (float) ($_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true));
|
||
|
||
if ($requestStartedAt <= (float) $pending['ready_at']) {
|
||
return null;
|
||
}
|
||
|
||
$lock = @fopen(storage_path('.update-finish.lock'), 'c');
|
||
|
||
if ($lock === false || ! flock($lock, LOCK_EX | LOCK_NB)) {
|
||
return null; // Läuft gerade in einer anderen Anfrage.
|
||
}
|
||
|
||
$userId = isset($pending['user_id']) ? (int) $pending['user_id'] : null;
|
||
|
||
try {
|
||
if (! is_file(self::pendingPath())) {
|
||
return null; // Eine andere Anfrage war schneller.
|
||
}
|
||
|
||
@set_time_limit(0);
|
||
@ignore_user_abort(true);
|
||
|
||
$this->progress->set(80, 'migrate', 'Datenbank wird aktualisiert …');
|
||
$migrationCount = $this->migrations->run();
|
||
|
||
$this->progress->set(90, 'cache', 'Zwischenspeicher werden geleert …');
|
||
$this->clearCaches();
|
||
@file_put_contents(storage_path('.migrations-fingerprint'), $this->migrations->fingerprint());
|
||
|
||
Audit::log('update.installed', [
|
||
'channel' => $pending['channel'] ?? null,
|
||
'sha' => $pending['sha'] ?? null,
|
||
'migrations' => $migrationCount,
|
||
'files' => (int) ($pending['files'] ?? 0),
|
||
], $userId);
|
||
|
||
$this->progress->set(100, 'done', 'Aktualisierung abgeschlossen.');
|
||
|
||
return ['sha' => (string) ($pending['sha'] ?? ''), 'migrations' => $migrationCount, 'files' => (int) ($pending['files'] ?? 0)];
|
||
} catch (Throwable $e) {
|
||
$message = 'Die neue Version ist installiert, aber die Datenbank konnte nicht aktualisiert werden: '.$e->getMessage();
|
||
$this->progress->fail($message);
|
||
Log::error('Update: Migrationen fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]);
|
||
Audit::log('update.failed', ['channel' => $pending['channel'] ?? null, 'sha' => $pending['sha'] ?? null, 'migrations' => 0, 'error' => $message, 'code' => null], $userId);
|
||
|
||
throw $e;
|
||
} finally {
|
||
// Nicht endlos wiederholen – ausstehende Migrationen holt RunPendingMigrations nach
|
||
@unlink(self::pendingPath());
|
||
$this->maintenance->deactivate();
|
||
flock($lock, LOCK_UN);
|
||
fclose($lock);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param array{sha: string|null, sha256: string|null} $headers
|
||
*/
|
||
private function verifyZip(string $file, array $headers): void
|
||
{
|
||
$handle = @fopen($file, 'rb');
|
||
$magic = $handle ? fread($handle, 2) : '';
|
||
|
||
if ($handle) {
|
||
fclose($handle);
|
||
}
|
||
|
||
if ($magic !== 'PK') {
|
||
throw new RuntimeException('Die Antwort des Update-Servers ist kein ZIP-Archiv (vermutlich eine Fehlerseite). Die installierte Version bleibt unverändert.');
|
||
}
|
||
|
||
if ($headers['sha256'] && ! hash_equals(strtolower($headers['sha256']), hash_file('sha256', $file))) {
|
||
throw new RuntimeException('Das heruntergeladene Archiv ist beschädigt (Prüfsumme stimmt nicht). Bitte erneut versuchen.');
|
||
}
|
||
}
|
||
|
||
private function clearCaches(): void
|
||
{
|
||
// Paketliste neu aufbauen – bootstrap/cache ist vor dem Updater geschützt, neue Pakete
|
||
// (z. B. Sanctum für die App) würden sonst nie geladen
|
||
foreach (['package:discover', 'cache:clear', 'view:clear', 'config:clear', 'route:clear', 'event:clear'] as $command) {
|
||
try {
|
||
Artisan::call($command);
|
||
} catch (Throwable $e) {
|
||
Log::warning("{$command} fehlgeschlagen: ".$e->getMessage());
|
||
}
|
||
}
|
||
|
||
// Bytecode-Cache verwerfen – sonst läuft noch eine Weile der alte Code.
|
||
if (function_exists('opcache_reset')) {
|
||
@opcache_reset();
|
||
}
|
||
}
|
||
}
|