This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 17:36:53 +01:00
1 parent 5b6d4a7903
commit 4d1087e357
160 files changed
+2407 -1933

No files matched your search

+2 -27
View File
@@ -1,7 +1,7 @@
"""Runtime install/update operations for deploy.py."""
from __future__ import annotations
from deploy_core import * # re-exported internal deployment primitives
from deploy_core import *
ACME_RUNTIME_NAMES = frozenset({'acme-python', 'acme-python.installing', 'acme-python.virtualenv-bootstrap'})
RUNTIME_STATE_NAMES = frozenset({'.geoip-update.lock'})
@@ -117,13 +117,11 @@ def restore_managed_acme_runtime(failed: Path, restored: Path) -> None:
except OSError:
shutil.copytree(source, target, symlinks=True)
def chown_tree(path: Path, uid: int, gid: int) -> None:
os.chown(path, uid, gid)
for child in path.rglob('*'):
os.chown(child, uid, gid, follow_symlinks=False)
def ensure_service_data_access(data: Path, account) -> None:
"""Repair the managed data-root metadata and verify service-user traversal.
@@ -153,7 +151,6 @@ def ensure_service_data_access(data: Path, account) -> None:
'check execute/search permissions on its parent directories (for example with namei -l).'
)
def switch(prefix: Path, release: str) -> None:
if not re.fullmatch(r'[A-Za-z0-9_.-]+', release) or '..' in release:
raise ValueError('Invalid release name.')
@@ -161,7 +158,6 @@ def switch(prefix: Path, release: str) -> None:
os.symlink('releases/' + release, temporary)
os.replace(temporary, prefix / 'current')
def running_release_matches(record: dict) -> bool:
"""Check the actual systemd process executable without publishing a version API.
@@ -181,7 +177,6 @@ def running_release_matches(record: dict) -> bool:
except (OSError, ValueError, KeyError, subprocess.SubprocessError):
return False
def admin_health_endpoint(record: dict) -> tuple[str, bool, str]:
"""Resolve the active persisted administration listener and scheme.
@@ -211,7 +206,6 @@ def admin_health_endpoint(record: dict) -> tuple[str, bool, str]:
if isinstance(values, list):
allowed_hosts = [str(value).strip() for value in values if str(value).strip()]
except (OSError, sqlite3.Error, ValueError, TypeError, json.JSONDecodeError):
# Fall back to the startup listener for old or uninitialized databases.
pass
host, port = (raw[1:].split(']:') if raw.startswith('[') else raw.rsplit(':', 1))
@@ -226,13 +220,11 @@ def admin_health_endpoint(record: dict) -> tuple[str, bool, str]:
connect_raw = f'[{connect_host}]:{port}' if ':' in connect_host else f'{connect_host}:{port}'
return connect_raw, tls, authority
def healthy(record: dict, version: str, attempts: int = 30) -> bool:
raw, tls, health_host = admin_health_endpoint(record)
host, port = (raw[1:].split(']:') if raw.startswith('[') else raw.rsplit(':', 1))
for _ in range(attempts):
if tls:
# Local liveness probe only; the admin certificate may be self-signed.
conn = http.client.HTTPSConnection(host, int(port), timeout=2, context=ssl._create_unverified_context())
else:
conn = http.client.HTTPConnection(host, int(port), timeout=2)
@@ -251,7 +243,6 @@ def healthy(record: dict, version: str, attempts: int = 30) -> bool:
time.sleep(1)
return False
def stage(binary: Path, prefix: Path, user: str, sha: str) -> tuple[str, str]:
release = 'build-' + sha[:24]
releases = prefix / 'releases'; releases.mkdir(mode=0o755, exist_ok=True); os.chmod(releases, 0o755)
@@ -265,16 +256,13 @@ def stage(binary: Path, prefix: Path, user: str, sha: str) -> tuple[str, str]:
shutil.rmtree(directory); raise
if directory.is_symlink() or (directory / 'rust-proxy').is_symlink() or digest(directory / 'rust-proxy') != sha:
raise ValueError('Staged binary checksum mismatch.')
# Never execute the supplied binary as root, even for its version banner.
result = run(['runuser', '-u', user, '--', str(directory / 'rust-proxy'), '--version'], capture_output=True, text=True, timeout=15)
matched = re.fullmatch(r'(?:rust-proxy|RustProxy) (\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*', result.stdout)
if not matched:
raise ValueError('Binary did not return a RustProxy version.')
return release, matched[1]
def backup_stopped(record: dict, prefix: Path) -> Path:
# Service stop must happen before this call: ACME files and SQLite form one backup.
data = Path(record['data_dir'])
lock_fd = os.open(data / 'process.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
@@ -290,7 +278,6 @@ def backup_stopped(record: dict, prefix: Path) -> Path:
finally:
os.close(lock_fd)
def restore_service_unit(backup: Path) -> None:
saved = backup / 'rustproxy.service'
if saved.exists():
@@ -299,7 +286,6 @@ def restore_service_unit(backup: Path) -> None:
UNIT_PATH.unlink(missing_ok=True)
run(['systemctl', 'daemon-reload'])
def reset_saved_config(data: Path) -> None:
"""Development-only reset of desired config while preserving auth/certs/audit data."""
database = data / 'config.sqlite3'
@@ -316,7 +302,6 @@ def reset_saved_config(data: Path) -> None:
connection.close()
print('Stored vhost/settings configuration cleared; account, certificates and other private data were preserved.')
def service_failure_details() -> str:
chunks: list[str] = []
commands = (
@@ -333,7 +318,6 @@ def service_failure_details() -> str:
pass
return '\n'.join(chunks)[-8000:]
def stop_for_managed_update(data: Path) -> None:
"""Ask RustProxy 0.14.0+ to force hot cache into the enabled cold tier before exit.
@@ -349,26 +333,21 @@ def stop_for_managed_update(data: Path) -> None:
finally:
marker.unlink(missing_ok=True)
def update(record: dict, binary: Path, sha: str, start: bool, refresh_geoip: bool = False, reset_config: bool = False) -> dict:
prefix = Path(record['prefix']); data = Path(record['data_dir']); account = pwd.getpwnam(record['user'])
geoip_lock_fd: int | None = None
geoip_stage: Path | None = None
try:
# Repair missing or stale installer-owned shell setup on upgrades.
install_shell_path(prefix)
check_shell_path(prefix)
# Repair stale ownership before stopping the running service.
ensure_service_data_access(data, account)
release, version = stage(binary, prefix, record['user'], sha)
geoip_names: list[str] = []
if refresh_geoip:
# Shared lock with the runtime worker prevents concurrent upgrades.
geoip_lock_fd = acquire_geoip_update_lock(data, account.pw_uid, account.pw_gid)
try:
geoip_stage, geoip_names = prepare_geoip_update(data, prefix)
except GeoipUnavailable as error:
# GeoIP is refreshed best-effort: the update must not be blocked by a flaky download.
print(f'WARNING: GeoIP refresh skipped, keeping the installed country data: {error}', file=sys.stderr)
geoip_stage, geoip_names = None, []
active = subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], check=False, stdout=subprocess.DEVNULL).returncode == 0
@@ -399,7 +378,7 @@ def update(record: dict, binary: Path, sha: str, start: bool, refresh_geoip: boo
print('New release diagnostics:\n' + details, file=sys.stderr)
stop_for_managed_update(data)
failed = data.with_name(data.name + '.failed-' + uuid.uuid4().hex[:12])
data.rename(failed) # keep the failed generation for diagnosis; do not delete it
data.rename(failed)
copy_data(backup / 'data', data)
restore_managed_acme_runtime(failed, data)
chown_tree(data, account.pw_uid, account.pw_gid)
@@ -420,7 +399,6 @@ def update(record: dict, binary: Path, sha: str, start: bool, refresh_geoip: boo
shutil.rmtree(geoip_stage, ignore_errors=True)
release_geoip_update_lock(geoip_lock_fd)
def install(record: dict, binary: Path, sha: str, start: bool, install_geoip: bool = False) -> dict:
import grp
prefix = Path(record['prefix']); data = Path(record['data_dir'])
@@ -448,7 +426,6 @@ def install(record: dict, binary: Path, sha: str, start: bool, install_geoip: bo
switch(prefix, release)
install_shell_path(prefix)
install_logrotate(record)
# Record is written even if initial startup fails, so an update can repair it.
write_private(prefix / 'install.json', json.dumps(record, indent=2).encode())
write_private(UNIT_PATH, service_unit(record).encode(), 0o644)
run(['systemctl', 'daemon-reload']); run(['systemctl', 'enable', SERVICE])
@@ -458,5 +435,3 @@ def install(record: dict, binary: Path, sha: str, start: bool, install_geoip: bo
run(['systemctl', 'stop', SERVICE])
raise RuntimeError('Installed but startup failed. Data was retained; inspect journalctl -u rustproxy.')
return record