Files
smeta-web/scripts/migrate_python314_cron.py
T

73 lines
3.0 KiB
Python

"""Move only the production smeta-web cron jobs to the service's Python 3.14.
Run after the production service has started successfully. Preserve the complete
old crontab for a manual rollback; never alter jobs belonging to other projects.
"""
import fcntl
import re
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
PYTHON_BIN = "/home/mcp-user/python314-migration-venv/bin/python"
APP_DIR = "/home/mcp-user/smeta-web"
BACKUP_DIR = Path("/data_safe/backups/smeta-web")
_APP_CD = re.compile(r"(?:^|[\s'\"])cd\s+" + re.escape(APP_DIR) + r"(?=\s|$)")
_OLD_PYTHON = re.compile(r"(?<![\w/])(?:/usr/bin/)?python3(?=\s)")
_ANY_OLD_PYTHON = re.compile(r"(?<!\w)python3(?=\s)")
def rewrite_crontab(crontab: str) -> tuple[str, int]:
lines = []
changed = 0
for line in crontab.splitlines(keepends=True):
if not line.lstrip().startswith("#") and _APP_CD.search(line):
updated = _OLD_PYTHON.sub(PYTHON_BIN, line)
if _ANY_OLD_PYTHON.search(updated):
raise ValueError("неизвестный Python в задании smeta-web: " + line[:80])
changed += updated != line
line = updated
lines.append(line)
return "".join(lines), changed
def _crontab() -> str:
return subprocess.run(["crontab", "-l"], check=True, capture_output=True,
text=True).stdout
def main() -> None:
lock = Path.home() / ".smeta-cron-install.lock"
with lock.open("a+") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
before = _crontab()
if not any(_APP_CD.search(line) for line in before.splitlines()):
raise RuntimeError("cron smeta-web не найден: установка остановлена")
after, changed = rewrite_crontab(before)
if not changed:
print("cron smeta-web уже использует Python 3.14")
return
if not Path(PYTHON_BIN).is_file():
raise RuntimeError("venv Python 3.14 отсутствует")
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
with tempfile.NamedTemporaryFile(mode="w", prefix=f"crontab-before-python314-{stamp}-",
suffix=".txt", dir=BACKUP_DIR, delete=False) as saved:
saved.write(before)
backup = Path(saved.name)
try:
subprocess.run(["crontab", "-"], input=after, text=True, check=True,
capture_output=True)
if _crontab() != after:
raise RuntimeError("crontab после установки не совпадает с проверенным текстом")
except Exception:
subprocess.run(["crontab", str(backup)], check=True, capture_output=True)
raise
print(f"cron smeta-web: переведено {changed} строк; исходник {backup}")
if __name__ == "__main__":
main()