Files
canina/scripts/install-stage-principal-cleanup.py
2026-10-24 13:04:35 +00:00

59 lines
2.4 KiB
Python

#!/usr/bin/env python3
"""Install the reviewed retry worker only through the guarded host CI deploy."""
import os
from pathlib import Path
import subprocess
import tempfile
def install(root, source, run):
base = root / 'opt/services/canina'
units = root / 'etc/systemd/system'
journal = base / 'stage-principal-cleanup'
base.mkdir(parents=True, exist_ok=True)
units.mkdir(parents=True, exist_ok=True)
if journal.is_symlink():
raise ValueError('Unsafe journal')
journal.mkdir(mode=0o700, exist_ok=True)
st = journal.lstat()
if not journal.is_dir() or st.st_uid != os.getuid() or st.st_mode & 0o777 != 0o700:
raise ValueError('Unsafe journal')
# Never touch existing intents. Atomic replacement avoids truncated workers.
payloads = [('stage-principal-cleanup.py', base, 0o755)] + [
('canina-stage-principal-cleanup.' + suffix, units, 0o644)
for suffix in ('service', 'timer')]
for name, dest, mode in payloads:
fd, temporary = tempfile.mkstemp(prefix='.cleanup-install-', dir=dest)
try:
with os.fdopen(fd, 'wb') as output:
output.write((source / name).read_bytes())
os.fchmod(output.fileno(), mode)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, dest / name)
directory = os.open(dest, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
for command in [
['systemctl', 'daemon-reload'],
['systemctl', 'enable', '--now', 'canina-stage-principal-cleanup.timer'],
['systemctl', 'is-enabled', '--quiet', 'canina-stage-principal-cleanup.timer'],
['systemctl', 'is-active', '--quiet', 'canina-stage-principal-cleanup.timer'],
]:
run(command)
if __name__ == '__main__':
if (os.getuid() != 0 or Path('/.dockerenv').exists()
or Path('/run/.containerenv').exists()
or os.environ.get('GITHUB_ACTIONS', os.environ.get('GITEA_ACTIONS')) != 'true'):
raise SystemExit('Guarded host CI deployment required')
os.umask(0o077)
install(Path('/'), Path(__file__).resolve().parent,
lambda command: subprocess.run(command, check=True, timeout=60))