Files
Investidor-V2/tools/demography-deployment-backup.php
T
2026-11-21 20:58:19 +02:00

101 lines
7.1 KiB
PHP

<?php
// The operational database is read-only; restore writes only to the named isolated QA server.
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
ini_set('zend.exception_ignore_args', '1');
$root = dirname(__DIR__);
$app = require $root.'/bootstrap/app.php';
(new LoadEnvironmentVariables)->bootstrap($app);
(new LoadConfiguration)->bootstrap($app);
$c = config('database.connections.'.config('database.default'));
throw_unless($c['driver'] === 'pgsql' && empty($c['url']) && $c['host'] === '127.0.0.1' && (int) $c['port'] === 5432 && $c['database'] === 'investemoz', RuntimeException::class, 'Confirmed operational target required.');
$source = new PDO('pgsql:host=127.0.0.1;port=5432;dbname=investemoz', $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$source->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
$identity = $source->query("SELECT current_database() AS database,inet_server_port() AS port,current_setting('transaction_read_only') AS read_only")->fetch(PDO::FETCH_ASSOC);
throw_unless($identity['database'] === 'investemoz' && (int) $identity['port'] === 5432 && $identity['read_only'] === 'on', RuntimeException::class, 'Actual operational identity differs.');
$stamp = gmdate('Ymd_His');
$clone = 'demography_restore_'.$stamp.'_test';
$directory = $root.'/storage/app/private/demography-deployment/'.$stamp;
mkdir($directory, 0700, true);
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
$run = static function (array $args, string $password) use ($directory): void {
$process = new Process($args, null, ['PGPASSWORD' => $password]);
$process->setTimeout(300);
$process->run();
if (! $process->isSuccessful()) {
file_put_contents($directory.'/failure.json', json_encode(['tool' => basename($args[0]), 'exit' => $process->getExitCode()], JSON_THROW_ON_ERROR));
throw new RuntimeException('Backup/restore command failed; private diagnostic retained.');
}
};
$dump = $directory.'/database.dump';
$snapshot = $source->query('SELECT pg_export_snapshot()')->fetchColumn();
$run([$bin.'pg_dump.exe', '-h', '127.0.0.1', '-p', '5432', '-U', $c['username'], '-d', 'investemoz', '-Fc', '--snapshot='.$snapshot, '-f', $dump], $c['password']);
$qa = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=postgres', 'demography_qa', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
throw_unless((int) $qa->query('SELECT inet_server_port()')->fetchColumn() === 55441 && preg_match('/^demography_restore_\d{8}_\d{6}_test$/', $clone) === 1, RuntimeException::class, 'Restore target refused.');
$qa->exec('CREATE DATABASE "'.$clone.'"');
$run([$bin.'pg_restore.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'demography_qa', '-d', $clone, '--exit-on-error', '--no-owner', '--no-privileges', $dump], '');
$restored = new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$clone, 'demography_qa', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$restored->exec('BEGIN READ ONLY');
$tables = [];
foreach ($source->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC) as $table) {
$name = '"'.str_replace('"', '""', $table['schemaname']).'"."'.str_replace('"', '""', $table['tablename']).'"';
$sql = 'SELECT row_to_json(t)::text FROM '.$name.' t ORDER BY row_to_json(t)::text';
$a = $source->query($sql)->fetchAll(PDO::FETCH_COLUMN);
$b = $restored->query($sql)->fetchAll(PDO::FETCH_COLUMN);
// PostgreSQL installations have different collations; compare the exact byte multiset.
sort($a, SORT_STRING);
sort($b, SORT_STRING);
throw_unless($a === $b, RuntimeException::class, 'Restored table differs; do not deploy.');
$tables[$name] = ['count' => count($a), 'sha256' => hash('sha256', implode("\n", $a))];
}
$documents = $source->query('SELECT DISTINCT storage_key FROM documents WHERE storage_key IS NOT NULL')->fetchAll(PDO::FETCH_COLUMN);
$source->exec('ROLLBACK');
$restored->exec('ROLLBACK');
$zipPath = $directory.'/files.zip';
$zip = new ZipArchive;
throw_unless($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::EXCL) === true, RuntimeException::class);
$hashes = [];
$add = static function (string $file, string $member) use ($zip, &$hashes): void {
throw_unless(is_file($file) && $zip->addFile($file, $member), RuntimeException::class, 'Backup source unavailable.');
$hashes[$member] = hash_file('sha256', $file);
};
$privateRoot = realpath($root.'/storage/app/private');
foreach ($documents as $relative) {
$file = realpath($privateRoot.'/'.$relative);
throw_unless($file && str_starts_with(strtolower($file), strtolower($privateRoot.DIRECTORY_SEPARATOR)), RuntimeException::class, 'Document unavailable for recovery.');
$add($file, 'private/'.str_replace('\\', '/', substr($file, strlen($privateRoot) + 1)));
}
foreach (['app', 'routes', 'config', 'database/migrations', 'public/build'] as $folder) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root.'/'.$folder, FilesystemIterator::SKIP_DOTS)) as $file) {
if ($file->isFile()) {
$relative = str_replace('\\', '/', substr($file->getPathname(), strlen($root) + 1));
$add($file->getPathname(), 'code/'.$relative);
}
}
}
$add($root.'/.env', 'runtime/.env');
$zip->close();
$read = new ZipArchive;
throw_unless($read->open($zipPath) === true, RuntimeException::class);
foreach ($hashes as $member => $sha) {
$bytes = $read->getFromName($member);
throw_unless(is_string($bytes) && hash_equals($sha, hash('sha256', $bytes)), RuntimeException::class, 'File archive verification failed.');
$path = $directory.'/files-restored/'.$member;
if (! is_dir(dirname($path))) {
mkdir(dirname($path), 0700, true);
}
throw_unless(file_put_contents($path, $bytes) !== false && hash_file('sha256', $path) === $sha, RuntimeException::class, 'File restore verification failed.');
}
$read->close();
$proof = ['target' => ['database' => 'investemoz', 'port' => 5432], 'restore_target' => ['database' => $clone, 'port' => 55441],
'backup_at' => gmdate(DATE_ATOM), 'restore_verified' => true, 'files_verified' => true, 'tables' => $tables, 'file_count' => count($hashes),
'dump_path' => $dump, 'dump_sha256' => hash_file('sha256', $dump), 'files_path' => $zipPath, 'files_sha256' => hash_file('sha256', $zipPath),
'environment_sha256' => hash_file('sha256', $root.'/.env'), 'previous_manifest_sha256' => hash_file('sha256', $root.'/public/build/manifest.json'),
'decision' => 'Proprietário, 13/11/2026: homologar e disponibilizar no portal operacional local investemoz:5432, incluindo três ficheiros e Macate/Vanduzi.'];
file_put_contents($root.'/storage/app/private/demography-deployment/backup.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
echo json_encode(['restore_verified' => true, 'files_verified' => true, 'tables' => count($tables), 'files' => count($hashes), 'restore_target' => $clone], JSON_THROW_ON_ERROR).PHP_EOL;