Files
Investidor-V2/outputs/investmoz-parques-L1-QA-20261016/backup-restore-QA.py
T
nala cef6e201c7
tests / ci (push) Canceled after 0s
versao nrgocios 2
2026-10-16 20:11:05 +02:00

24 lines
2.4 KiB
Python

from pathlib import Path
import datetime,hashlib,json,subprocess,zipfile,sys
label=sys.argv[1]if len(sys.argv)>1 else '';assert label in ['', 'final']
out=Path(__file__).resolve().parent;private=Path('C:/Users/macbook/.config/investmoz/parques-L1-QA-20261016');qa=private/'source';backup=private/('restore-proof-'+label if label else 'restore-proof');assert not backup.exists();backup.mkdir()
pg=Path('C:/Program Files/PostgreSQL/17/bin');args=['-h','127.0.0.1','-p','55441','-U','postgres'];db='parks_l1_restore_20261016'+('_final'if label else '')+'_test'
assert subprocess.run([str(pg/'psql.exe'),*args,'-d','parks_l1_20261016_test','-Atc','SELECT inet_server_port()'],capture_output=True,text=True,check=True).stdout.strip()=='55441'
dump=backup/'QA.dump';subprocess.run([str(pg/'pg_dump.exe'),*args,'-d','parks_l1_20261016_test','-Fc','-f',str(dump)],check=True,capture_output=True)
subprocess.run([str(pg/'createdb.exe'),*args,db],check=True,capture_output=True)
subprocess.run([str(pg/'pg_restore.exe'),*args,'-d',db,'--exit-on-error','--no-owner','--no-privileges',str(dump)],check=True,capture_output=True)
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest();files=qa/'storage/app/private';manifest={p.relative_to(files).as_posix():sha(p)for p in files.rglob('*')if p.is_file()};archive=backup/'QA-files.zip'
with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED)as z:
for n in manifest:z.write(files/n,n)
extracted=backup/'files';extracted.mkdir()
with zipfile.ZipFile(archive)as z:
assert z.testzip()is None
for n in z.namelist():assert(extracted/n).resolve().is_relative_to(extracted.resolve())
z.extractall(extracted)
assert all(sha(extracted/n)==h for n,h in manifest.items())
# Reuse private QA key, override the restored DB before any service provider is booted.
boot=(out/'boot-QA.php').read_text('utf-8').replace("if($v!==null){putenv", "if($v!==null){if($k==='DB_DATABASE')$v='"+db+"';putenv").replace("$c['database']!=='parks_l1_20261016_test'", "$c['database']!=='"+db+"'")
(out/'boot-restored-QA.php').write_text(boot,'utf-8')
result={'verified_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'source':'parks_l1_20261016_test:55441','restore':db+':55441','dump_sha256':sha(dump),'files_zip_sha256':sha(archive),'files_extracted_and_SHA256_verified':len(manifest),'active_database_connections':0,'backup_contains_private_data_not_shared':True}
(out/'BACKUP-RESTAURO-QA.json').write_text(json.dumps(result,indent=2),'utf-8');print(json.dumps(result))