Files
compras/scripts/prepare-public-demonstration.py
T
nala 47649bd46c
tests / ci (push) Canceled after 0s
commit compras1 3011
2026-11-30 09:33:36 +02:00

106 lines
6.8 KiB
Python

"""Run over authenticated SSH: prepare an isolated synthetic installation, never switch live."""
import base64
import hashlib
import json
import os
from pathlib import Path
import secrets
import shutil
import subprocess
import sys
import uuid
import zipfile
def run(args, **kwargs):
result = subprocess.run(args, text=True, capture_output=True, **kwargs)
if result.returncode:
raise RuntimeError(f"Command failed: {args[0]} {args[1:3]}\n{result.stderr[-1800:]}\n{result.stdout[-1800:]}")
return result.stdout
def main():
assert os.geteuid() == 0 and sys.argv[1] == '--prepare-authorized-demo'
archive = Path('/root/compras-presentation-20261129.zip')
assert hashlib.sha256(archive.read_bytes()).hexdigest() == sys.argv[2]
base = Path('/var/www/compras-deploy')
previous = (base / 'current').resolve(strict=True)
assert previous.is_relative_to(base / 'releases')
assert Path('/var/www/html/compras.tempo.co.mz').resolve() == previous
demo = base / 'demonstration-20261129'
release = base / 'releases/presentation-20261129'
assert not demo.exists() and not release.exists(), 'Refusing to overwrite a prepared demonstration'
demo.mkdir(mode=0o750)
release.mkdir(mode=0o755)
access = Path('/root/compras-demo-access.json')
assert not access.exists(), 'Preserve existing private presentation credentials'
labels = {'admin': 'Administração', 'admin_review': 'Administração suplente', 'requester': 'Requisitante', 'head': 'Chefia',
'procurement': 'Compras', 'finance': 'Finanças preparação', 'finance_review': 'Finanças revisão', 'warehouse': 'Armazém', 'direction': 'Direcção', 'auditor': 'Auditoria'}
access.write_text(json.dumps({key: {'name': label+' - Demonstração', 'email': key+'@demo.compras.tempo.co.mz', 'password': secrets.token_urlsafe(20)} for key, label in labels.items()}, ensure_ascii=False, indent=2))
os.chmod(access, 0o600)
(demo / 'previous-release.txt').write_text(str(previous))
run(['rsync', '-a', '--exclude=/.env', '--exclude=/storage', '--exclude=/.git', '--exclude=/bootstrap/cache/*.php', str(previous)+'/', str(release)+'/'])
with zipfile.ZipFile(archive) as package:
for info in package.infolist():
assert not info.filename.startswith('/') and '..' not in Path(info.filename).parts
package.extractall(release)
storage = demo / 'storage'
for folder in ['app/private', 'app/public', 'framework/cache/data', 'framework/sessions', 'framework/views', 'framework/testing/private', 'logs']:
(storage / folder).mkdir(parents=True, exist_ok=True, mode=0o750)
(release / 'storage').symlink_to(storage, target_is_directory=True)
database = 'compras_demo_20261129'
role = 'compras_demo_app_20261129'
password = secrets.token_hex(32)
existing = run(['runuser', '-u', 'postgres', '--', 'psql', '-Atc', f"SELECT datname FROM pg_database WHERE datname='{database}'"])
assert not existing.strip(), 'Demonstration database already exists'
run(['runuser', '-u', 'postgres', '--', 'psql', '-v', 'ON_ERROR_STOP=1'], input=f"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;\nCREATE DATABASE {database} OWNER {role};\nREVOKE ALL ON DATABASE {database} FROM PUBLIC;\n")
settings = {
'APP_NAME': 'Compras — Demonstração', 'APP_ENV': 'production', 'APP_DEBUG': 'false',
'APP_KEY': 'base64:'+base64.b64encode(secrets.token_bytes(32)).decode(),
'APP_URL': 'https://compras.tempo.co.mz', 'APP_TIMEZONE': 'Africa/Maputo', 'COMPRAS_DEMONSTRATION': 'true',
'DB_CONNECTION': 'pgsql', 'DB_HOST': '127.0.0.1', 'DB_PORT': '5432', 'DB_DATABASE': database, 'DB_USERNAME': role, 'DB_PASSWORD': password,
'SESSION_DRIVER': 'database', 'SESSION_SECURE_COOKIE': 'true', 'SESSION_COOKIE': 'compras_presentation_session',
'CACHE_STORE': 'database', 'QUEUE_CONNECTION': 'database', 'MAIL_MAILER': 'log', 'LOG_LEVEL': 'warning',
'SGC_PUBLIC_NAVIGATION': 'true', 'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true',
'COMPRAS_RUNTIME_ROOT': str(release / 'presentation-runtime/finance'),
'COMPRAS_RUNTIME_SHA256': '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7',
'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4()), 'COMPRAS_RUNTIME_SYNTHETIC_ONLY': 'true',
'PAYABLE_SOURCE_INSTANCE': 'compras-presentation-'+str(uuid.uuid4()),
'COMPRAS_PRIVATE_STORAGE_PATH': str(storage / 'framework/testing/private'),
'COMPRAS_INVENTORY_CONVERSION_ENABLED': 'false', 'COMPRAS_INVENTORY_ROOT': str(release / 'presentation-runtime/inventory'),
'COMPRAS_ORDER_CANCELLATION_ENABLED': 'false', 'COMPRAS_ORDER_CANCELLATION_ROOT': str(release / 'presentation-runtime/cancellation'),
}
for key, package in [('COMMON_BUDGET_PATH', 'budget-control'), ('COMMON_PAYABLES_PATH', 'payables'), ('COMMON_PURCHASING_PATH', 'purchasing')]:
settings[key] = str(release / 'presentation-runtime/finance' / package)
features = json.loads((release / 'presentation-runtime/features.json').read_text())
settings.update({key: 'false' for key in features})
env_file = demo / '.env'
def write_env():
env_file.write_text(''.join(key+'='+json.dumps(value, ensure_ascii=False)+'\n' for key, value in settings.items()))
os.chmod(env_file, 0o640)
shutil.chown(env_file, group='www-data')
write_env()
(release / '.env').symlink_to(env_file)
run(['php', 'artisan', 'migrate', '--force', '--no-interaction'], cwd=release)
preparation = run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+database, '--expected-role='+role,
'--operator=Tempo presentation deployment', '--reason=Owner authorised isolated synthetic public demonstration', '--apply'], cwd=release)
settings.update({key: 'true' for key in features})
settings.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false',
'COMPRAS_INVENTORY_CONVERSION_ENABLED': 'true', 'COMPRAS_ORDER_CANCELLATION_ENABLED': 'true'})
write_env()
run(['chown', '-R', 'www-data:www-data', str(storage), str(release / 'bootstrap/cache')])
run(['chmod', '-R', 'g+rX', str(demo)])
run(['chown', 'root:www-data', str(demo)])
run(['php', 'artisan', 'config:cache'], cwd=release)
run(['chown', '-R', 'www-data:www-data', str(release / 'bootstrap/cache')])
(demo / 'prepared.json').write_text(json.dumps({'state': 'prepared_not_live', 'previous_release': str(previous), 'release': str(release),
'database': database, 'role': role, 'installation_id': settings['COMPRAS_RUNTIME_INSTALLATION_ID'], 'runtime_preparation': json.loads(preparation.strip().splitlines()[-1]),
'synthetic_only': True, 'live_link_changed': False}, indent=2))
print((demo / 'prepared.json').read_text())
if __name__ == '__main__':
main()