548 lines
24 KiB
Python
548 lines
24 KiB
Python
#!/usr/bin/env python3
|
|
"""Deploy FitOS na staging ODWOLANY LOKALNIE NA HOSTZIE (bez SSH/scp).
|
|
|
|
Orkiestrator auto-deploya: webhook Gitei -> agent (ops/deploy/agent/listener.py)
|
|
-> ten skrypt jako user `fitosdeploy`. Działa też ręcznie na hoście jako
|
|
awaryjny fallback (ten sam mechanizm, bez flagi agenta = bez bramki migracji).
|
|
|
|
Kroki: blokada flock (wspoldzielona z recznym deploy.py i kazdym innym runem:
|
|
plik `.deploy.lock` w katalogu NADRZEDNYM nad STACK_DIR — przetrwa swap
|
|
.now/.old) -> git fetch -> kontrola `[skip deploy]` w head-commicie -> bramka
|
|
destrukcyjnych migracji (diff stary SHA z RELEASE -> nowy SHA; statusy A i M
|
|
skanowane, usuniecie D tylko ostrzezenie — `--no-renames`, zeby rename nie
|
|
ukryl destrukcyjnej migracji) -> pg_dump (RAZ na run, przed pierwsza proba) ->
|
|
git archive + swap drzewa stosu (STACK_DIR, domyslnie
|
|
/var/lib/fitos-stack/fitos-staging; .new/.old, .env i RELEASE NIE sa
|
|
nadpisywane, w .env podmieniany jest wylacznie GIT_SHA -> build-arg admina) ->
|
|
docker compose build -> up -d ->
|
|
/health -> smoke web + smoke login/refresh. Cala sekwencja build/up/health/
|
|
smoke max 3 proby; po 3 nieudanych status FAILED, bez zadnego cofania.
|
|
|
|
Ochrona bazy danych:
|
|
- kazdy deploy zaczyna sie od dumpa `pg_dump` (bez dumpa deploy nie startuje),
|
|
- nowe migracje z DROP/TRUNCATE/DELETE/RENAME zatrzymuja auto-deploy
|
|
(BLOCKED_MIGRATION); ominiecia wylacznie swiadoma flaga --allow-destructive,
|
|
- skrypt NIE ZAWIERA zadnej sciezki kasowania wolumenow — to asercja testow
|
|
w ops/deploy/test/. Wolumeny sa external i przetrwaja kazdy deploy.
|
|
- dwa deploye nigdy nie graja na tym samym drzewie naraz: flock na
|
|
.deploy.lock w katalogu nadrzednym STACK_DIR (tego samego plika trzyma
|
|
sie krytyczne sekcje zdalne recznego deploy.py).
|
|
|
|
Konfiguracja (env albo plik agenta FITOS_AGENT_CONFIG, domyslnie
|
|
~/.config/fitos-deploy-agent/agent.env):
|
|
AGENT_HOME, STACK_DIR, AGENT_REPO, GIT_REMOTE_URL, DEPLOY_REF,
|
|
DB_CONTAINER, DEPLOY_TRIGGER, DEPLOY_LOG_KEEP, BACKUP_KEEP
|
|
|
|
Uzycie:
|
|
hostdeploy.py # deploy DEPLOY_REF (domyslnie origin/main)
|
|
hostdeploy.py --ref <sha> # deploy wskazanego SHA
|
|
hostdeploy.py --ref <sha> --force # ignoruj marker [skip deploy]
|
|
hostdeploy.py --ref <sha> --no-smoke # pomin smoke login/refresh
|
|
hostdeploy.py --ref <sha> --allow-destructive # run reczny na hoście: swiadome
|
|
# podejscie do migracji niszczacej dane
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from http.cookiejar import CookieJar
|
|
from pathlib import Path
|
|
|
|
try:
|
|
import fcntl # Linux (host); na Windowsie (testy dev) blokada plikowa jest pomijana
|
|
except ImportError: # pragma: no cover - Windows
|
|
fcntl = None
|
|
|
|
DEPLOY_DIR = Path(__file__).resolve().parent
|
|
# fetch ma padnac odrazu przy braku dostepu, nie czekac na pytania o dane logowania
|
|
os.environ.setdefault("GIT_TERMINAL_PROMPT", "0")
|
|
CODE_DIRS = ("api", "admin", "app", "web", "ops/deploy")
|
|
MIG_DIR = "api/prisma/migrations"
|
|
DEPLOY_MARKER = "[skip deploy]"
|
|
MAX_ATTEMPTS = 3
|
|
HEALTH_MAX_WAIT_S = 180
|
|
BUILD_TIMEOUT_S = 3600
|
|
UP_TIMEOUT_S = 600
|
|
EXIT_OK = 0
|
|
EXIT_FAILED = 1
|
|
EXIT_BLOCKED = 2
|
|
LOCK_NAME = ".deploy.lock" # w STACK_DIR/../ — poza wymienianym drzewem, ten sam plik co deploy.py
|
|
|
|
# destrukcyjne DDL w migration.sql — wykrywane przez bramke auto-deploya
|
|
DESTRUCTIVE_PATTERNS = (
|
|
re.compile(r"\bDROP\s+TABLE\b", re.IGNORECASE),
|
|
re.compile(r"\bDROP\s+(COLUMN|SCHEMA|DATABASE)\b", re.IGNORECASE),
|
|
re.compile(r"\bTRUNCATE\b", re.IGNORECASE),
|
|
re.compile(r"\bDELETE\s+FROM\b", re.IGNORECASE),
|
|
re.compile(r"\bRENAME\s+(COLUMN|TO)\b", re.IGNORECASE),
|
|
re.compile(r"\bALTER\s+TABLE\b[^;]*\bRENAME\b", re.IGNORECASE),
|
|
)
|
|
|
|
|
|
class DeployError(Exception):
|
|
"""Blad pojedynczej proby deploya — nadaje sie do ponownej proby."""
|
|
|
|
|
|
def log(msg: str) -> None:
|
|
print(f"[{datetime.now(timezone.utc).isoformat(timespec='seconds')}] {msg}", flush=True)
|
|
|
|
|
|
def run_cmd(args: list[str], cwd: Path | None = None, timeout: int | None = None,
|
|
check: bool = True, echo: bool = True) -> subprocess.CompletedProcess:
|
|
proc = subprocess.run(args, cwd=str(cwd) if cwd else None, capture_output=True,
|
|
text=True, timeout=timeout)
|
|
if echo or proc.returncode != 0:
|
|
out = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
|
|
for line in out.splitlines():
|
|
log(f" | {line}")
|
|
if check and proc.returncode != 0:
|
|
raise DeployError(f"polecenie nieudane (exit {proc.returncode}): {' '.join(args)}")
|
|
return proc
|
|
|
|
|
|
def load_kv(path: Path) -> dict[str, str]:
|
|
cfg: dict[str, str] = {}
|
|
if not path.is_file():
|
|
return cfg
|
|
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
line = raw.strip()
|
|
if not line or line.startswith("#") or "=" not in line:
|
|
continue
|
|
key, value = line.split("=", 1)
|
|
cfg[key.strip()] = value.strip()
|
|
return cfg
|
|
|
|
|
|
class Ctx:
|
|
def __init__(self, args: argparse.Namespace) -> None:
|
|
agent_cfg_path = Path(os.environ.get("FITOS_AGENT_CONFIG")
|
|
or Path.home() / ".config" / "fitos-deploy-agent" / "agent.env")
|
|
merged = load_kv(agent_cfg_path)
|
|
merged.update({k: v for k, v in os.environ.items() if k.startswith(("AGENT_", "STACK_", "GIT_", "DB_", "DEPLOY_"))})
|
|
stack_env_path = Path(merged.get("STACK_DIR") or Path.home() / "fitos-staging") / ".env"
|
|
try:
|
|
stack_env = load_kv(stack_env_path)
|
|
except PermissionError as err:
|
|
raise SystemExit(
|
|
f"brak dostepu do {stack_env_path} (uprawnienia ustawil kto inny — np. reczny deploy.py "
|
|
"jako inny user). Napraw na hoście (ACL katalogu stosu, nie chmod 600 — chmod kasuje "
|
|
"maske ACL): sudo setfacl -R -d -m u:fitosdeploy:rw,u:homelab:rw "
|
|
+ str(stack_env_path.parent)
|
|
+ " i sudo chmod 640 " + str(stack_env_path) + f". Szczegoly: {err}"
|
|
)
|
|
# .env stosu na hoście jest ZRODLEM PRAWDY dla portow/wolumenow/hasla admina
|
|
for key, value in stack_env.items():
|
|
merged.setdefault(key, value)
|
|
|
|
def get(key: str, default: str = "") -> str:
|
|
return os.environ.get(key) or merged.get(key) or default
|
|
|
|
self.agent_mode = bool(args.agent)
|
|
self.ref = args.ref
|
|
self.force = args.force
|
|
self.no_smoke = args.no_smoke
|
|
self.allow_destructive = args.allow_destructive
|
|
self.agent_home = Path(get("AGENT_HOME", str(Path.home() / "fitos-staging-agent")))
|
|
self.stack_dir = Path(get("STACK_DIR", "/var/lib/fitos-stack/fitos-staging"))
|
|
self.repo_path = Path(get("AGENT_REPO", str(self.agent_home / "repo")))
|
|
self.git_remote = get("GIT_REMOTE_URL", "http://127.0.0.1:11000/Tisachi/FitOS.git")
|
|
self.deploy_ref = args.ref or get("DEPLOY_REF", "origin/main")
|
|
self.db_container = get("DB_CONTAINER", "fitos-db-staging")
|
|
self.db_name = "fitos"
|
|
self.trigger = get("DEPLOY_TRIGGER", "webhook" if self.agent_mode else "manual")
|
|
self.log_keep = int(get("DEPLOY_LOG_KEEP", "50"))
|
|
self.backup_keep = int(get("BACKUP_KEEP", "20"))
|
|
self.logs_dir = self.agent_home / "logs"
|
|
self.backups_dir = self.agent_home / "backups"
|
|
self.releases_log = self.agent_home / "RELEASES.log"
|
|
# blokada poza wymienianym drzewem stosu (.new/.old) — stabilna sciezka
|
|
self.lock_path = self.stack_dir.parent / LOCK_NAME
|
|
self.stack_env = stack_env
|
|
for key in ("ADMIN_HOST_PORT", "APP_HOST_PORT", "API_HOST_PORT", "WEB_HOST_PORT",
|
|
"PGDATA_VOLUME", "UPLOADS_VOLUME"):
|
|
if not stack_env.get(key):
|
|
raise SystemExit(f"BRAK {key} w {stack_env_path} — .env stosu na hoście musi istniec i byc uzupelniony.")
|
|
self.admin_port = stack_env["ADMIN_HOST_PORT"]
|
|
self.api_port = stack_env["API_HOST_PORT"]
|
|
self.web_port = stack_env["WEB_HOST_PORT"]
|
|
self.volumes = [stack_env["PGDATA_VOLUME"], stack_env["UPLOADS_VOLUME"]]
|
|
self.admin_email = stack_env.get("FITOS_FIRST_ADMIN_EMAIL") or "admin@fitos.local"
|
|
self.admin_password = stack_env.get("FITOS_FIRST_ADMIN_PASSWORD") or ""
|
|
|
|
|
|
def acquire_deploy_lock(ctx: Ctx):
|
|
"""Wykluczenie wzajemne: agent, reczny run i sekcje zdalne deploy.py trzymaja
|
|
TE SAMO flock na .deploy.lock (katalog nadrzedny STACK_DIR — poza swapem
|
|
drzewa). Czekamy blokujaaco, nie przerywamy: drugi deploy po prostu startuje
|
|
pozniej. Zwraca uchwyt pliku do zamkniecia (None = Windows/testy dev)."""
|
|
if fcntl is None:
|
|
return None
|
|
try:
|
|
fh = os.open(str(ctx.lock_path), os.O_RDWR | os.O_CREAT, 0o666)
|
|
try:
|
|
os.chmod(str(ctx.lock_path), 0o666) # obu userom (fitosdeploy, homelab) trzeba *rw*
|
|
except OSError:
|
|
pass # nie nasz plik — wtedy musi wystarczyc ACL/umask katalogu
|
|
except OSError as err:
|
|
raise SystemExit(
|
|
f"nie moge otworzyc blokady {ctx.lock_path}: {err} — napraw na hoście: "
|
|
"sudo setfacl -d -m u:fitosdeploy:rw,u:homelab:rw " + str(ctx.lock_path.parent)
|
|
)
|
|
try:
|
|
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
log("INNY DEPLOY W TOKU — czekam na blokade .deploy.lock...")
|
|
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
return fh
|
|
|
|
|
|
def compose_cmd(ctx: Ctx, *parts: str) -> list[str]:
|
|
return ["docker", "compose", "-f", str(ctx.stack_dir / "ops/deploy/compose.yml"),
|
|
"--env-file", str(ctx.stack_dir / ".env"), *parts]
|
|
|
|
|
|
def rotate_keep(directory: Path, pattern: str, keep: int) -> None:
|
|
files = sorted(directory.glob(pattern), key=lambda p: p.stat().st_mtime)
|
|
for old in files[:-keep] if keep > 0 else files:
|
|
old.unlink(missing_ok=True)
|
|
|
|
|
|
def old_release_sha(ctx: Ctx) -> str:
|
|
release = ctx.stack_dir / "RELEASE"
|
|
if not release.is_file():
|
|
return ""
|
|
return load_kv(release).get("sha", "")
|
|
|
|
|
|
def fetch_and_resolve(ctx: Ctx) -> str:
|
|
if not (ctx.repo_path / ".git").exists():
|
|
raise SystemExit(f"brak repo agenta w {ctx.repo_path} — sklonuj wczesniej (runbook w ops/docs/srodowiska.md)")
|
|
run_cmd(["git", "-C", str(ctx.repo_path), "fetch", "--quiet", "origin"], timeout=300)
|
|
verify = run_cmd(["git", "-C", str(ctx.repo_path), "rev-parse", "--verify", "--quiet",
|
|
f"{ctx.deploy_ref}^{{commit}}"], check=False)
|
|
if verify.returncode != 0:
|
|
raise SystemExit(f"ref '{ctx.deploy_ref}' nie istnieje po fetchu origin")
|
|
return verify.stdout.strip()
|
|
|
|
|
|
def commit_message(ctx: Ctx, sha: str) -> str:
|
|
return run_cmd(["git", "-C", str(ctx.repo_path), "show", "-s", "--format=%B", sha], echo=False).stdout
|
|
|
|
|
|
def has_skip_marker(ctx: Ctx, sha: str) -> bool:
|
|
return DEPLOY_MARKER in commit_message(ctx, sha)
|
|
|
|
|
|
def find_new_migrations(repo_path: Path, old_sha: str, new_sha: str) -> list[tuple[str, str]]:
|
|
"""(sciezka, tresc) plikow migration.sql DODANYCH (A) lub ZMIENIONYCH (M)
|
|
miedzy old_sha i new_sha. `--no-renames`: przeniesienie destrukcyjnej
|
|
migracji do nowego katalogu jest tu widziane jako dodanie (inaczej git
|
|
ukrylby je jako R100). Usuniecie (D) nie jest cofnieciem schema — tylko
|
|
ostrzezenie, bo Prisma i tak zna stary wpis."""
|
|
diff = run_cmd(["git", "-C", str(repo_path), "diff", "--name-status", "--no-renames",
|
|
f"{old_sha}..{new_sha}", "--", f"{MIG_DIR}/"], check=False, echo=False)
|
|
found: list[tuple[str, str]] = []
|
|
for line in diff.stdout.splitlines():
|
|
parts = line.split("\t")
|
|
if len(parts) < 2:
|
|
continue
|
|
status, path = parts[0][0], parts[1]
|
|
if status == "D":
|
|
log(f"UWAGA: usunieto plik migracji {path} — schema NIE zostaje cofnieta")
|
|
continue
|
|
if status not in ("A", "M") or not path.endswith("migration.sql"):
|
|
continue
|
|
show = run_cmd(["git", "-C", str(repo_path), "show", f"{new_sha}:{path}"], check=False, echo=False)
|
|
if show.returncode == 0:
|
|
found.append((path, show.stdout))
|
|
return found
|
|
|
|
|
|
def scan_destructive(files: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
|
hits: list[tuple[str, str]] = []
|
|
for path, sql in files:
|
|
for pattern in DESTRUCTIVE_PATTERNS:
|
|
match = pattern.search(sql)
|
|
if match:
|
|
hits.append((path, match.group(0)))
|
|
break
|
|
return hits
|
|
|
|
|
|
def volumes_ok(ctx: Ctx) -> None:
|
|
for vol in ctx.volumes:
|
|
proc = run_cmd(["docker", "volume", "inspect", vol], check=False)
|
|
if proc.returncode != 0:
|
|
raise DeployError(f"brak wolumenu danych {vol!r} — deploy przerwany (nazwy w .env stosu)")
|
|
|
|
|
|
def predeploy_dump(ctx: Ctx, sha: str) -> None:
|
|
"""pg_dump ZAWSZE przed up -d. Bez dumpa deploy nie startuje."""
|
|
inspect = run_cmd(["docker", "inspect", "-f", "{{.State.Running}}", ctx.db_container], check=False)
|
|
if inspect.stdout.strip().lower() != "true":
|
|
log("kontener bazy NIE działa — pomijam dump (pierwszy deploy? kontrola wolumenow dalej obowiazuje)")
|
|
volumes_ok(ctx)
|
|
return
|
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
|
out_file = ctx.backups_dir / f"predeploy-{stamp}-{sha[:8]}.sql"
|
|
with out_file.open("wb") as dump_out:
|
|
proc = subprocess.run(["docker", "exec", ctx.db_container, "pg_dump", "-U", ctx.db_name, ctx.db_name],
|
|
stdout=dump_out, stderr=subprocess.PIPE, text=True)
|
|
if proc.returncode != 0 or out_file.stat().st_size == 0:
|
|
out_file.unlink(missing_ok=True)
|
|
raise DeployError(f"pg_dump nieudany (zanim cos zmienimy): {proc.stderr.strip()[:300]}")
|
|
log(f"dump bazy: {out_file.name} ({out_file.stat().st_size / (1024 * 1024):.1f} MB)")
|
|
rotate_keep(ctx.backups_dir, "predeploy-*.sql", ctx.backup_keep)
|
|
|
|
|
|
def stamp_git_sha(env_path: Path, sha: str) -> None:
|
|
"""GIT_SHA w .env stosu: compose.yml interpolicies go jako build-arg admina
|
|
(VITE_GIT_SHA -> stopka wersji w panelu). Reszta .env (sekrety) nietknięta."""
|
|
if not env_path.is_file():
|
|
return
|
|
lines = env_path.read_text(encoding="utf-8").splitlines()
|
|
for i, line in enumerate(lines):
|
|
if line.strip().startswith("GIT_SHA="):
|
|
lines[i] = f"GIT_SHA={sha}"
|
|
env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
return
|
|
lines.append(f"GIT_SHA={sha}")
|
|
env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
|
|
|
|
def sync_tree(ctx: Ctx, sha: str) -> None:
|
|
"""git archive -> .new, przeniesienie .env/RELEASE ze starego drzewa, swap (.old)."""
|
|
archive = ctx.agent_home / f"fitos-src-{sha[:12]}.tar.gz"
|
|
try:
|
|
run_cmd(["git", "-C", str(ctx.repo_path), "archive", "--format=tar.gz", "-o", str(archive),
|
|
sha, "--", *CODE_DIRS], timeout=300)
|
|
new_dir = Path(str(ctx.stack_dir) + ".new")
|
|
old_dir = Path(str(ctx.stack_dir) + ".old")
|
|
if new_dir.exists():
|
|
try:
|
|
shutil.rmtree(new_dir)
|
|
except OSError as err:
|
|
raise DeployError(
|
|
f"nie moge posprzatac {new_dir} (po cudzym runie wlasnosc/tryby nie do zapisania): {err}"
|
|
" — uporzadkuj na hoście: sudo chown -R fitosdeploy:fitosdeploy "
|
|
+ str(new_dir) + " " + str(old_dir)
|
|
)
|
|
new_dir.mkdir(parents=True)
|
|
with tarfile.open(archive, "r:gz") as tar:
|
|
try:
|
|
tar.extractall(new_dir, filter="data")
|
|
except TypeError: # python < 3.12 bez filtra
|
|
tar.extractall(new_dir)
|
|
for keep in (".env", "RELEASE"):
|
|
src = ctx.stack_dir / keep
|
|
if src.is_file():
|
|
shutil.copy2(src, new_dir / keep)
|
|
# copy2 przenosi tryb zrodlowy (np. 600 od recznego deployu) i kasuje nim
|
|
# maske odziedziczonych ACL-i — normalizujemy 660: oba wpisy ACL
|
|
# (u:homelab, u:fitosdeploy) pozostaja skuteczne po swapie
|
|
for keep in (".env", "RELEASE"):
|
|
copied = new_dir / keep
|
|
if copied.is_file():
|
|
os.chmod(copied, 0o660)
|
|
stamp_git_sha(new_dir / ".env", sha)
|
|
if old_dir.exists():
|
|
shutil.rmtree(old_dir)
|
|
if ctx.stack_dir.exists():
|
|
ctx.stack_dir.rename(old_dir)
|
|
new_dir.rename(ctx.stack_dir)
|
|
if old_dir.exists():
|
|
try:
|
|
shutil.rmtree(old_dir)
|
|
except OSError as err:
|
|
# stale .po swapie drzewo jest juz podmienione — nie wolno przez
|
|
# to failowac proby (sprzatniemy przy nastepnym syncu lub recznie)
|
|
log(f"UWAGA: nie udalo sie usunac {old_dir}: {err} — kolejny sync sprobuje ponownie")
|
|
log(f"drzewo zrodlowe podmienione w {ctx.stack_dir} (.env zachowany)")
|
|
finally:
|
|
archive.unlink(missing_ok=True)
|
|
|
|
|
|
def stack_build(ctx: Ctx) -> None:
|
|
log("docker compose build (stary stos wciaz sluzy)")
|
|
run_cmd(compose_cmd(ctx, "build"), timeout=BUILD_TIMEOUT_S)
|
|
|
|
|
|
def stack_up(ctx: Ctx) -> None:
|
|
log("docker compose up -d")
|
|
run_cmd(compose_cmd(ctx, "up", "-d"), timeout=UP_TIMEOUT_S)
|
|
|
|
|
|
def http_get(url: str, timeout: int = 10) -> tuple[int, str]:
|
|
try:
|
|
with urllib.request.urlopen(url, timeout=timeout) as resp:
|
|
return resp.status, resp.read().decode("utf-8", "replace")
|
|
except urllib.error.HTTPError as err:
|
|
return err.code, err.read().decode("utf-8", "replace")
|
|
except Exception as err: # noqa: BLE001 — kazdy blad sieciowy = brak zdrowia
|
|
log(f" health/smoke: {url} -> {err}")
|
|
return 0, ""
|
|
|
|
|
|
def wait_health(ctx: Ctx) -> None:
|
|
url = f"http://127.0.0.1:{ctx.api_port}/health"
|
|
deadline = time.monotonic() + HEALTH_MAX_WAIT_S
|
|
while time.monotonic() < deadline:
|
|
status, body = http_get(url)
|
|
if status == 200 and '"ok"' in body:
|
|
log("API healthy (/health)")
|
|
return
|
|
time.sleep(3)
|
|
run_cmd(compose_cmd(ctx, "logs", "--tail", "40", "api"), check=False)
|
|
raise DeployError(f"/health nieosiagalny pod {url} po {HEALTH_MAX_WAIT_S} s")
|
|
|
|
|
|
def smoke_web(ctx: Ctx) -> None:
|
|
status, body = http_get(f"http://127.0.0.1:{ctx.web_port}/")
|
|
if status != 200 or "fitos" not in body.lower():
|
|
raise DeployError(f"smoke web: GET / = {status}, 'FitOS' w HTML={'fitos' in body.lower()}")
|
|
log("smoke web OK (GET / = 200 + FitOS)")
|
|
|
|
|
|
def smoke_session(ctx: Ctx) -> None:
|
|
"""login+refresh przez port admina (same-origin). 401 = ostrzezenie (haslo
|
|
admina bywa zmienione po seedzie), nie fail."""
|
|
base = f"http://127.0.0.1:{ctx.admin_port}"
|
|
jar = CookieJar()
|
|
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
|
login_body = f'{{"email":"{ctx.admin_email}","password":"{ctx.admin_password}"}}'.encode()
|
|
try:
|
|
req = urllib.request.Request(f"{base}/api/v1/auth/login", data=login_body,
|
|
headers={"Content-Type": "application/json", "X-Client": "admin"},
|
|
method="POST")
|
|
resp = opener.open(req, timeout=15)
|
|
status = resp.status
|
|
except urllib.error.HTTPError as err:
|
|
status = err.code
|
|
except Exception as err: # noqa: BLE001
|
|
raise DeployError(f"smoke login: blad polaczenia: {err}")
|
|
if status == 401:
|
|
log("UWAGA: smoke login = 401 — haslo admina zmienione po seedzie; pomijam sesje (nie jest to regresja deployu)")
|
|
return
|
|
if status != 200:
|
|
raise DeployError(f"smoke login wrocil {status} zamiast 200")
|
|
try:
|
|
req = urllib.request.Request(f"{base}/api/v1/auth/refresh", method="POST",
|
|
headers={"X-Client": "admin"})
|
|
resp = opener.open(req, timeout=15)
|
|
status, body = resp.status, resp.read().decode("utf-8", "replace")
|
|
except urllib.error.HTTPError as err:
|
|
status, body = err.code, err.read().decode("utf-8", "replace")
|
|
if status != 200 or "accessToken" not in body:
|
|
raise DeployError(f"smoke refresh = {status}, accessToken={'accessToken' in body} — sesja NIE dziala")
|
|
log("smoke sesji OK (login+refresh 200 + nowy accessToken)")
|
|
|
|
|
|
def attempt(ctx: Ctx, sha: str, attempt_no: int) -> None:
|
|
log(f"--- proba {attempt_no}/{MAX_ATTEMPTS} dla {sha[:12]} ---")
|
|
sync_tree(ctx, sha)
|
|
stack_build(ctx)
|
|
volumes_ok(ctx)
|
|
stack_up(ctx)
|
|
wait_health(ctx)
|
|
smoke_web(ctx)
|
|
if not ctx.no_smoke:
|
|
smoke_session(ctx)
|
|
|
|
|
|
def write_release(ctx: Ctx, sha: str) -> None:
|
|
content = (
|
|
f"ref={ctx.deploy_ref}\n"
|
|
f"sha={sha}\n"
|
|
f"date={datetime.now(timezone.utc).isoformat(timespec='seconds')}\n"
|
|
f"trigger={ctx.trigger}\n"
|
|
)
|
|
(ctx.stack_dir / "RELEASE").write_text(content, encoding="utf-8")
|
|
log(f"RELEASE zapisany: {sha[:12]} (trigger={ctx.trigger})")
|
|
|
|
|
|
def release_log(ctx: Ctx, sha: str, outcome: str, duration_s: float) -> None:
|
|
line = (f"{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} | {sha[:12]} | "
|
|
f"{ctx.deploy_ref} | {outcome} | {duration_s:.0f}s\n")
|
|
with ctx.releases_log.open("a", encoding="utf-8") as fh:
|
|
fh.write(line)
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Deploy FitOS na staging uruchamiany lokalnie na hoście.")
|
|
parser.add_argument("--ref", default=None, help="ref/SHA do wystawienia (domyslnie DEPLOY_REF, np. origin/main)")
|
|
parser.add_argument("--agent", action="store_true", help="uruchomienie z agenta: wlacza bramke destrukcyjnych migracji")
|
|
parser.add_argument("--force", action="store_true", help="ignoruj marker [skip deploy] w commicie")
|
|
parser.add_argument("--no-smoke", action="store_true", help="pomin smoke login+refresh")
|
|
parser.add_argument("--allow-destructive", action="store_true", help="zignoruj bronke migracji (swiadoma decyzja, tylko run reczny na hoście)")
|
|
args = parser.parse_args()
|
|
|
|
ctx = Ctx(args)
|
|
ctx.logs_dir.mkdir(parents=True, exist_ok=True)
|
|
ctx.backups_dir.mkdir(parents=True, exist_ok=True)
|
|
lock_fh = acquire_deploy_lock(ctx)
|
|
started = time.monotonic()
|
|
|
|
sha = fetch_and_resolve(ctx)
|
|
outcome = ""
|
|
try:
|
|
if has_skip_marker(ctx, sha) and not ctx.force:
|
|
log(f"commit {sha[:12]} zawiera '{DEPLOY_MARKER}' — pomijam")
|
|
outcome = "SKIPPED"
|
|
return EXIT_OK
|
|
|
|
old_sha = old_release_sha(ctx)
|
|
if not old_sha:
|
|
log("brak SHA w RELEASE — pierwszy deploy: bramka migracji bez diffu (dump i kontrola wolumenow obowiazuja)")
|
|
else:
|
|
new_files = find_new_migrations(ctx.repo_path, old_sha, sha)
|
|
hits = scan_destructive(new_files)
|
|
if hits:
|
|
listed = ", ".join(f"{p} ({m})" for p, m in hits)
|
|
if ctx.agent_mode and not ctx.allow_destructive:
|
|
log(f"BLOKUJE destrukcyjna migracja: {listed}")
|
|
outcome = "BLOCKED_MIGRATION"
|
|
return EXIT_BLOCKED
|
|
log(f"UWAGA: destrukcyjna migracja {listed} — kontynuuje (brak flagi agenta lub --allow-destructive)")
|
|
|
|
# dump RAZ na run — kolejne proby nie mnoza kopii tej samej bazy
|
|
try:
|
|
predeploy_dump(ctx, sha)
|
|
except DeployError as err:
|
|
log(f"przerwany deploy bez kopii bazy: {err}")
|
|
outcome = "FAILED_DUMP"
|
|
return EXIT_FAILED
|
|
|
|
for attempt_no in range(1, MAX_ATTEMPTS + 1):
|
|
try:
|
|
attempt(ctx, sha, attempt_no)
|
|
except Exception as err: # noqa: BLE001 — kazdy blad proby = kolejna proba
|
|
log(f"proba {attempt_no} nieudana: {err}")
|
|
if attempt_no == MAX_ATTEMPTS:
|
|
outcome = f"FAILED po {MAX_ATTEMPTS} probach"
|
|
return EXIT_FAILED
|
|
time.sleep(5)
|
|
continue
|
|
write_release(ctx, sha)
|
|
outcome = "OK"
|
|
return EXIT_OK
|
|
finally:
|
|
if outcome:
|
|
release_log(ctx, sha, outcome, time.monotonic() - started)
|
|
rotate_keep(ctx.logs_dir, "deploy-*.log", ctx.log_keep)
|
|
if lock_fh is not None:
|
|
os.close(lock_fh)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|