Files

112 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Check that production receives the exact revision already tested on release dev."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
SHA = re.compile(r"[0-9a-f]{40}\Z")
def _git(stage: Path, *args: str) -> str:
result = subprocess.run(["git", "-C", str(stage), *args],
check=True, capture_output=True, text=True)
return result.stdout.strip()
def _index_hash(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def _stage_problems(expected: str, stage: Path) -> list[str]:
problems = []
try:
if _git(stage, "symbolic-ref", "--quiet", "--short", "HEAD") != "release":
problems.append("дев-каталог не на ветке release")
if _git(stage, "rev-parse", "HEAD") != expected:
problems.append("дев-каталог уже на другом коммите")
except (OSError, subprocess.CalledProcessError):
problems.append("не удалось прочесть git дев-каталога")
try:
lines = (stage / ".predeploy-stamp").read_text().splitlines()
if len(lines) < 3 or lines[0] != expected or lines[2] != "full: not-ui+ui":
problems.append("нет полного тестового следа этого коммита на деве")
except OSError:
problems.append("нет тестового следа на деве")
return problems
def verify(expected: str, stage: Path, prod_index: Path, marker: Path) -> list[str]:
stage, prod_index, marker = Path(stage), Path(prod_index), Path(marker)
if not SHA.fullmatch(expected):
return ["неверный SHA кандидата"]
problems = _stage_problems(expected, stage)
try:
data = json.loads(marker.read_text())
if not isinstance(data, dict) or data.get("sha") != expected:
problems.append("дев не подтвердил точный коммит")
elif data.get("index_sha256") != _index_hash(prod_index):
problems.append("боевой рабочий индекс изменился после проверки дев-версии")
except (OSError, ValueError, TypeError):
problems.append("нет корректного подтверждения дев-версии")
return problems
def mark_ready(expected: str, stage: Path, prod_index: Path, marker: Path) -> None:
stage, prod_index, marker = Path(stage), Path(prod_index), Path(marker)
if not SHA.fullmatch(expected):
raise ValueError("неверный SHA кандидата")
problems = _stage_problems(expected, stage)
if problems:
raise ValueError("; ".join(problems))
data = {"sha": expected, "index_sha256": _index_hash(prod_index),
"tested_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
marker.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=".release-ready-", dir=marker.parent)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as stream:
json.dump(data, stream, ensure_ascii=False)
stream.write("\n")
os.replace(tmp, marker)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("mode", choices=("verify", "mark"))
parser.add_argument("sha")
parser.add_argument("stage", type=Path)
parser.add_argument("prod_index", type=Path)
parser.add_argument("marker", type=Path)
args = parser.parse_args()
if args.mode == "mark":
try:
mark_ready(args.sha, args.stage, args.prod_index, args.marker)
except (OSError, ValueError) as error:
print(f"release gate: {error}")
return 2
print(f"release ready: {args.sha}")
return 0
problems = verify(args.sha, args.stage, args.prod_index, args.marker)
for problem in problems:
print(f"release gate: {problem}")
return 2 if problems else 0
if __name__ == "__main__":
raise SystemExit(main())