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

105 lines
4.3 KiB
Python

"""Consolidate the selected installation's storage and single recurring service."""
from pathlib import Path
import hashlib
import json
import os
import pwd
import shutil
import subprocess
base = Path('/var/www/compras-deploy')
root = (base/'current').resolve()
assert root == base/'releases/presentation-20261129'
storage = (root/'storage').resolve()
assert storage == base/'demonstration-20261129/storage'
backup = Path('/var/backups/compras-presentation-20261129/consolidation')
assert backup.is_dir()
env = (root/'.env').resolve()
old = storage/'framework/testing/private'
new = storage/'app/private'
assert old.is_dir() and not old.is_symlink() and not new.is_symlink()
original = env.read_text()
assert 'COMPRAS_PRIVATE_STORAGE_PATH='+str(old) in original or 'COMPRAS_PRIVATE_STORAGE_PATH="'+str(old)+'"' in original
files = {}
for source in old.rglob('*'):
assert not source.is_symlink()
if not source.is_file():
continue
relative = source.relative_to(old)
digest = hashlib.sha256(source.read_bytes()).hexdigest()
dest = new/relative
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists():
assert hashlib.sha256(dest.read_bytes()).hexdigest() == digest
else:
shutil.copy2(source, dest)
assert hashlib.sha256(dest.read_bytes()).hexdigest() == digest
files[str(relative)] = digest
owner = pwd.getpwnam('www-data')
for p in [new]+list(new.rglob('*')):
os.chown(p, owner.pw_uid, owner.pw_gid)
p.chmod(0o700 if p.is_dir() else 0o600)
lines = original.splitlines()
for i, line in enumerate(lines):
if line.startswith('COMPRAS_PRIVATE_STORAGE_PATH='):
lines[i] = 'COMPRAS_PRIVATE_STORAGE_PATH='+json.dumps(str(new))
elif line.startswith('APP_NAME='):
lines[i] = 'APP_NAME="Compras"'
temp = env.with_name(env.name+'.release-next')
temp.write_text('\n'.join(lines)+'\n')
attrs = env.stat()
os.chown(temp, attrs.st_uid, attrs.st_gid)
temp.chmod(attrs.st_mode & 0o777)
os.replace(temp, env)
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
subprocess.run(['systemctl', 'stop', 'compras-demo-operations.timer'], check=True)
subprocess.run(['systemctl', 'disable', 'compras-demo-operations.timer'], check=True)
active = subprocess.run(['systemctl', 'is-active', 'compras-demo-operations.service'], capture_output=True, text=True).stdout.strip()
assert active != 'active', 'Prior service is still running; do not overlap'
for suffix in ['service', 'timer']:
oldunit = Path('/etc/systemd/system/compras-demo-operations.'+suffix)
if oldunit.exists():
shutil.copy2(oldunit, backup/oldunit.name)
service = '''[Unit]
Description=Compras recurring operations
After=network.target postgresql.service
[Service]
Type=oneshot
User=www-data
Group=www-data
WorkingDirectory=/var/www/compras-deploy/current
ExecStartPre=/usr/bin/php scripts/verify-compras-release.php /var/www/compras-deploy/current --installed
ExecStart=/usr/bin/php artisan sgc:approval-deadlines-tick
ExecStart=/usr/bin/php artisan sgc:replenishment-tick
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/www/compras-deploy/demonstration-20261129/storage
'''
timer = '''[Unit]
Description=Compras recurring operations timer
[Timer]
OnBootSec=60s
OnUnitActiveSec=60s
Unit=compras-operations.service
[Install]
WantedBy=timers.target
'''
for suffix, contents in [('service', service), ('timer', timer)]:
unit = Path('/etc/systemd/system/compras-operations.'+suffix)
assert not unit.exists(), 'Preserve an existing canonical service'
unit.write_text(contents)
unit.chmod(0o644)
subprocess.run(['systemctl', 'daemon-reload'], check=True)
subprocess.run(['systemctl', 'start', 'compras-operations.service'], check=True)
subprocess.run(['systemctl', 'restart', 'compras-operations.service'], check=True)
subprocess.run(['systemctl', 'enable', '--now', 'compras-operations.timer'], check=True)
proof = {'state': 'passed', 'release_id': json.loads((root/'compras-release.json').read_text())['release_id'],
'private_files_preserved': files, 'private_root': str(new), 'previous_private_root_preserved': True,
'single_timer': 'compras-operations.timer', 'start_and_restart': 'passed', 'business_records_migrated': False}
(backup/'operations.json').write_text(json.dumps(proof, indent=2)+'\n')
print(json.dumps(proof))