2026-10-14 04:49:53 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
"""Deploy FitOS na staging/prod WYLACZNIE z refa gita (git archive -> scp -> docker compose).
|
|
|
|
|
|
|
|
|
|
Stdlib + systemowe `git`, `ssh`, `scp` (opcjonalnie `sshpass` dla hasla SSH).
|
|
|
|
|
Konfiguracja srodowiska: deploy/.deploy.<env>.env (wzorce: .deploy.<env>.env.example).
|
|
|
|
|
|
|
|
|
|
Kroki: git fetch -> git archive <ref> (api admin app deploy) -> scp -> na hoście
|
|
|
|
|
.swap drzewa ~/fitos-<env> (.old) -> plik RELEASE -> .env (chmod 600, sekrety
|
|
|
|
|
generowane i zapisywane z powrotem lokalnie) -> docker compose up -d --build ->
|
|
|
|
|
health-check /health -> smoke sesji (login+refresh przez port fronta) -> ps + RELEASE.
|
|
|
|
|
|
|
|
|
|
Uzycie:
|
|
|
|
|
deploy/deploy.sh -e staging # pelny deploy origin/main
|
|
|
|
|
deploy/deploy.sh -e staging --ref v1.2.3 # deploy taga
|
|
|
|
|
deploy/deploy.sh -e staging --no-build # bez --build (obrazy aktualne)
|
|
|
|
|
deploy/deploy.sh -e staging --no-smoke # pomin smoke sesji
|
|
|
|
|
deploy/deploy.sh -e staging --logs # na koniec docker compose logs
|
|
|
|
|
deploy/deploy.sh -e staging --reset-db # TYLE STAGING: kasacja wolumenow + seed
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
import base64
|
|
|
|
|
import os
|
|
|
|
|
import secrets
|
|
|
|
|
import shutil
|
|
|
|
|
import string
|
|
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
import tempfile
|
|
|
|
|
import time
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
DEPLOY_DIR = Path(__file__).resolve().parent
|
|
|
|
|
REPO_ROOT = DEPLOY_DIR.parent
|
|
|
|
|
SUPPORTED_ENVS = ("staging", "prod")
|
|
|
|
|
SECRET_KEYS = ("JWT_ACCESS_SECRET", "JWT_REFRESH_SECRET", "FITOS_FIRST_ADMIN_PASSWORD")
|
|
|
|
|
# bez znakow specjalnych — pewne w .env, JSON i shella (bez kwotowania)
|
|
|
|
|
PASSWORD_CHARS = string.ascii_letters + string.digits + "-_"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def step(msg: str) -> None:
|
|
|
|
|
print(f"==> {msg}", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def ok(msg: str) -> None:
|
|
|
|
|
print(f" OK: {msg}", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def die(msg: str) -> "NoReturn": # type: ignore[valid-type]
|
|
|
|
|
print(f"BŁĄD: {msg}", file=sys.stderr, flush=True)
|
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- plik .deploy.<env>.env --------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def load_env_file(path: Path) -> dict[str, str]:
|
|
|
|
|
cfg: dict[str] = {}
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save_secret_lines(path: Path, secrets_to_store: dict[str, str]) -> None:
|
|
|
|
|
"""Zapis wygenerowanych sekretow do pliku .env ( podmieniajac puste wpisy)."""
|
|
|
|
|
lines = path.read_text(encoding="utf-8").splitlines()
|
|
|
|
|
for i, line in enumerate(lines):
|
|
|
|
|
stripped = line.strip()
|
|
|
|
|
for key, value in secrets_to_store.items():
|
|
|
|
|
if stripped.startswith(f"{key}="):
|
|
|
|
|
lines[i] = f"{key}={value}"
|
|
|
|
|
existing = {ln.split("=", 1)[0].strip() for ln in lines if "=" in ln and not ln.strip().startswith("#")}
|
|
|
|
|
for key, value in secrets_to_store.items():
|
|
|
|
|
if key not in existing:
|
|
|
|
|
lines.append(f"{key}={value}")
|
|
|
|
|
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def gen_password(length: int = 20) -> str:
|
|
|
|
|
return "".join(secrets.choice(PASSWORD_CHARS) for _ in range(length))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def fill_secrets(cfg: dict[str, str], env_path: Path) -> None:
|
|
|
|
|
dirty: dict[str, str] = {}
|
|
|
|
|
for key in ("JWT_ACCESS_SECRET", "JWT_REFRESH_SECRET"):
|
|
|
|
|
if not cfg.get(key):
|
|
|
|
|
cfg[key] = secrets.token_hex(32)
|
|
|
|
|
dirty[key] = cfg[key]
|
|
|
|
|
if not cfg.get("FITOS_FIRST_ADMIN_PASSWORD"):
|
|
|
|
|
cfg["FITOS_FIRST_ADMIN_PASSWORD"] = gen_password()
|
|
|
|
|
dirty["FITOS_FIRST_ADMIN_PASSWORD"] = cfg["FITOS_FIRST_ADMIN_PASSWORD"]
|
|
|
|
|
print(f" Wygenerowano haslo pierwszego admina: {cfg['FITOS_FIRST_ADMIN_PASSWORD']}", flush=True)
|
|
|
|
|
if dirty:
|
|
|
|
|
step(f"Zapis wygenerowanych sekretow do {env_path.relative_to(REPO_ROOT)}")
|
|
|
|
|
save_secret_lines(env_path, dirty)
|
|
|
|
|
ok("sekrety zapisane")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- git ---------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def run_git(args: list[str], check: bool = True, capture: bool = True) -> subprocess.CompletedProcess:
|
|
|
|
|
return subprocess.run(
|
|
|
|
|
["git", *args],
|
|
|
|
|
cwd=REPO_ROOT,
|
|
|
|
|
check=check,
|
|
|
|
|
capture_output=capture,
|
|
|
|
|
text=True,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def prepare_archive(ref: str) -> tuple[Path, str]:
|
|
|
|
|
step(f"git fetch origin (ref deployu: {ref})")
|
|
|
|
|
fetch = run_git(["fetch", "--quiet", "origin"], check=False)
|
|
|
|
|
if fetch.returncode != 0:
|
|
|
|
|
print(" ostrzezenie: git fetch nieudany — pracuje na lokalnym stanie refa", flush=True)
|
|
|
|
|
verify = run_git(["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], check=False)
|
|
|
|
|
if verify.returncode != 0:
|
|
|
|
|
die(f"ref '{ref}' nie istnieje (po fetchu origin).")
|
|
|
|
|
sha = verify.stdout.strip()
|
|
|
|
|
|
|
|
|
|
tree = run_git(["ls-tree", "--name-only", sha, "deploy/"], check=False).stdout
|
|
|
|
|
if "deploy/compose.yml" not in tree:
|
|
|
|
|
die(f"ref '{ref}' nie zawiera drzewa deploy/ — wystaw referencje z aktualnego main.")
|
|
|
|
|
|
|
|
|
|
fd, tmp_name = tempfile.mkstemp(prefix="fitos-deploy-", suffix=".tar.gz")
|
|
|
|
|
os.close(fd)
|
|
|
|
|
tar_path = Path(tmp_name)
|
|
|
|
|
step(f"git archive {sha[:12]} -> {tar_path.name}")
|
|
|
|
|
run_git(["archive", "--format=tar.gz", "-o", str(tar_path), sha, "--", "api", "admin", "app", "deploy"])
|
|
|
|
|
size_mb = tar_path.stat().st_size / (1024 * 1024)
|
|
|
|
|
ok(f"paczka {size_mb:.1f} MB")
|
|
|
|
|
return tar_path, sha
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- ssh/scp -------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
class Remote:
|
|
|
|
|
def __init__(self, cfg: dict[str, str]) -> None:
|
|
|
|
|
self.target = cfg.get("SSH_TARGET") or ""
|
|
|
|
|
if not self.target and cfg.get("SSH_HOST"):
|
|
|
|
|
self.target = f"{cfg.get('SSH_USER', '')}@{cfg['SSH_HOST']}"
|
|
|
|
|
if not self.target:
|
|
|
|
|
die("Brak SSH_TARGET w pliku .env (np. homelab lub user@host).")
|
|
|
|
|
self.password = cfg.get("SSH_PASSWORD") or None
|
|
|
|
|
self.use_sshpass = False
|
|
|
|
|
if self.password:
|
|
|
|
|
if shutil.which("sshpass"):
|
|
|
|
|
self.use_sshpass = True
|
|
|
|
|
else:
|
|
|
|
|
die("SSH_PASSWORD ustawione, ale brak sshpass w PATH — usun klucz/haslo albo zainstaluj sshpass.")
|
|
|
|
|
|
|
|
|
|
def _wrap(self, cmd: list[str]) -> tuple[list[str], dict[str, str]]:
|
|
|
|
|
env = dict(os.environ)
|
|
|
|
|
if self.use_sshpass:
|
|
|
|
|
env["SSH_PASSWORD"] = self.password or ""
|
|
|
|
|
cmd = ["sshpass", "-e", *cmd]
|
|
|
|
|
elif cmd and cmd[0] == "ssh":
|
|
|
|
|
cmd = [*cmd[:1], "-o", "BatchMode=yes", *cmd[1:]]
|
|
|
|
|
return cmd, env
|
|
|
|
|
|
|
|
|
|
def exec(self, script: str, timeout: int | None = None) -> str:
|
|
|
|
|
cmd, env = self._wrap(["ssh", "-o", "ConnectTimeout=15", self.target, "bash -s"])
|
|
|
|
|
proc = subprocess.run(cmd, input=script, capture_output=True, text=True, env=env, timeout=timeout)
|
|
|
|
|
if proc.returncode != 0:
|
|
|
|
|
detail = (proc.stderr or proc.stdout or "").strip()
|
|
|
|
|
die(f"polecenie zdalne nieudane (exit {proc.returncode}):\n{script}\n{detail}")
|
|
|
|
|
return proc.stdout
|
|
|
|
|
|
|
|
|
|
def check(self, script: str) -> subprocess.CompletedProcess:
|
|
|
|
|
cmd, env = self._wrap(["ssh", "-o", "ConnectTimeout=15", self.target, "bash -s"])
|
|
|
|
|
return subprocess.run(cmd, input=script, capture_output=True, text=True, env=env, timeout=60)
|
|
|
|
|
|
|
|
|
|
def put(self, local: Path, remote: str) -> None:
|
|
|
|
|
cmd, env = self._wrap(
|
|
|
|
|
["scp", "-q", "-o", "ConnectTimeout=15", str(local), f"{self.target}:{remote}"]
|
|
|
|
|
)
|
|
|
|
|
subprocess.run(cmd, check=True, env=env, timeout=600)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def compose(remote_dir: str) -> str:
|
|
|
|
|
return f"cd ~/{remote_dir} && docker compose -f deploy/compose.yml --env-file .env"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- kroki zdalne ---------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def migrate_legacy_project(remote: Remote, env_name: str) -> None:
|
|
|
|
|
"""Jednorazowa migracja: stary projekt 'fitos-alt' -> 'fitos-<env>' (wolumeny zostaja)."""
|
|
|
|
|
if env_name != "staging":
|
|
|
|
|
return
|
|
|
|
|
out = remote.exec(
|
|
|
|
|
"docker ps -aq --filter label=com.docker.compose.project=fitos-alt | tr '\\n' ' '\n"
|
|
|
|
|
).strip()
|
|
|
|
|
if not out:
|
|
|
|
|
return
|
|
|
|
|
step("Migracja starego projektu fitos-alt (kontenery zostana usuniete, wolumeny zostana)")
|
|
|
|
|
remote.exec(
|
|
|
|
|
f"docker rm -f {out} >/dev/null 2>&1 || true\n"
|
|
|
|
|
"docker network rm fitos-alt_default >/dev/null 2>&1 || true\n"
|
|
|
|
|
)
|
|
|
|
|
ok("stare kontenery fitos-alt usuniete")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def require_volumes(remote: Remote, volumes: list[str]) -> None:
|
|
|
|
|
missing = [v for v in volumes if remote.check(f"docker volume inspect {v!r} >/dev/null 2>&1").returncode != 0]
|
|
|
|
|
if not missing:
|
|
|
|
|
return
|
|
|
|
|
listing = remote.exec("docker volume ls --format '{{.Name}}' | grep -i fitos || true").strip()
|
|
|
|
|
die(
|
|
|
|
|
"Brak wolumen(ow) danych: " + ", ".join(missing)
|
|
|
|
|
+ "\n Wolumeny na hoście (fitos*):\n "
|
|
|
|
|
+ (listing or "(brak)")
|
|
|
|
|
+ "\n Nazwy sprawdz w deploy/.deploy.<env>.env; jezeli to swieze srodowisko,"
|
|
|
|
|
"\n utworz je swiadomie: docker volume create <nazwa>"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def sync_tree(remote: Remote, tar_path: Path, remote_dir: str, env_name: str) -> None:
|
|
|
|
|
remote_tar = f"/tmp/fitos-{env_name}-src.tgz"
|
|
|
|
|
step("Upload na host (scp)")
|
|
|
|
|
remote.put(tar_path, remote_tar)
|
|
|
|
|
ok(f"wyslano {remote_tar}")
|
|
|
|
|
step(f"Rozpakowanie do ~/{remote_dir} (stare drzewo -> .old)")
|
|
|
|
|
remote.exec(f"""
|
|
|
|
|
set -e
|
|
|
|
|
cd ~
|
|
|
|
|
rm -rf {remote_dir}.new
|
|
|
|
|
mkdir -p {remote_dir}.new
|
|
|
|
|
tar -xzf {remote_tar} -C {remote_dir}.new
|
|
|
|
|
rm -f {remote_tar}
|
|
|
|
|
rm -rf {remote_dir}.old
|
|
|
|
|
if [ -d {remote_dir} ]; then mv {remote_dir} {remote_dir}.old; fi
|
|
|
|
|
mv {remote_dir}.new {remote_dir}
|
|
|
|
|
rm -rf {remote_dir}.old
|
|
|
|
|
""")
|
|
|
|
|
ok(f"drzewo zrodlowe w ~/{remote_dir}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_remote_file(remote: Remote, rel_path: str, content: str, mode: str | None = None, remote_dir: str = "") -> None:
|
|
|
|
|
b64 = base64.b64encode(content.encode("utf-8")).decode("ascii")
|
|
|
|
|
perm = f" && chmod {mode} ~/{remote_dir}/{rel_path}" if mode else ""
|
|
|
|
|
remote.exec(
|
|
|
|
|
f"set -e && cd ~/{remote_dir} && printf '%s' '{b64}' | base64 -d > {rel_path}{perm}"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_release(remote: Remote, remote_dir: str, ref: str, sha: str) -> None:
|
|
|
|
|
who = run_git(["config", "user.name"], check=False).stdout.strip() or os.environ.get("USER") or "unknown"
|
|
|
|
|
content = (
|
|
|
|
|
f"ref={ref}\n"
|
|
|
|
|
f"sha={sha}\n"
|
|
|
|
|
f"date={datetime.now(timezone.utc).isoformat(timespec='seconds')}\n"
|
|
|
|
|
f"deployed_by={who}\n"
|
|
|
|
|
)
|
|
|
|
|
write_remote_file(remote, "RELEASE", content, remote_dir=remote_dir)
|
|
|
|
|
ok("RELEASE zapisany")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_stack_env(remote: Remote, remote_dir: str, cfg: dict[str, str], env_name: str) -> None:
|
|
|
|
|
lines = [
|
|
|
|
|
f"DEPLOY_ENV={env_name}",
|
|
|
|
|
f"JWT_ACCESS_SECRET={cfg['JWT_ACCESS_SECRET']}",
|
|
|
|
|
f"JWT_REFRESH_SECRET={cfg['JWT_REFRESH_SECRET']}",
|
|
|
|
|
f"FITOS_FIRST_ADMIN_EMAIL={cfg.get('FITOS_FIRST_ADMIN_EMAIL') or 'admin@fitos.local'}",
|
|
|
|
|
f"FITOS_FIRST_ADMIN_PASSWORD={cfg['FITOS_FIRST_ADMIN_PASSWORD']}",
|
|
|
|
|
f"LOG_LEVEL={cfg.get('LOG_LEVEL') or 'info'}",
|
|
|
|
|
f"COOKIE_SECURE={cfg.get('COOKIE_SECURE') or 'false'}",
|
|
|
|
|
f"TZ={cfg.get('TZ') or 'Europe/Warsaw'}",
|
|
|
|
|
f"ADMIN_HOST_PORT={cfg['ADMIN_HOST_PORT']}",
|
|
|
|
|
f"APP_HOST_PORT={cfg['APP_HOST_PORT']}",
|
|
|
|
|
f"API_HOST_PORT={cfg['API_HOST_PORT']}",
|
|
|
|
|
f"DB_HOST_PORT={cfg['DB_HOST_PORT']}",
|
|
|
|
|
f"PGDATA_VOLUME={cfg['PGDATA_VOLUME']}",
|
|
|
|
|
f"UPLOADS_VOLUME={cfg['UPLOADS_VOLUME']}",
|
|
|
|
|
]
|
|
|
|
|
if cfg.get("CORS_EXTRA_ORIGINS"):
|
|
|
|
|
lines.append(f"CORS_EXTRA_ORIGINS={cfg['CORS_EXTRA_ORIGINS']}")
|
|
|
|
|
write_remote_file(remote, ".env", "\n".join(lines) + "\n", mode="600", remote_dir=remote_dir)
|
|
|
|
|
ok(".env stosu (chmod 600) zapisany")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stack_build(remote: Remote, remote_dir: str) -> None:
|
|
|
|
|
# osobno PRZED podnizeniem starego stosu — budujemy w spokoju, przestoj to tylko restart
|
|
|
|
|
step("docker compose build (stary stos wciaz sluzy; pierwsze budowanie bywa dlugie)")
|
|
|
|
|
remote.exec(f"{compose(remote_dir)} build 2>&1", timeout=3600)
|
|
|
|
|
ok("obrazy zbudowane")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stack_up(remote: Remote, remote_dir: str) -> None:
|
|
|
|
|
step("docker compose up -d")
|
|
|
|
|
remote.exec(f"{compose(remote_dir)} up -d 2>&1", timeout=600)
|
|
|
|
|
ok("kontenery wystartowaly")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def reset_db(remote: Remote, remote_dir: str, volumes: list[str]) -> None:
|
|
|
|
|
step("reset bazy: compose down + kasacja wolumenow + ponowne utworzenie")
|
|
|
|
|
remote.exec(f"{compose(remote_dir)} down --remove-orphans 2>&1", timeout=300)
|
|
|
|
|
remote.exec("docker volume rm " + " ".join(volumes) + " 2>&1 && docker volume create " + volumes[0] + " && docker volume create " + volumes[1] + " 2>&1", timeout=120)
|
|
|
|
|
ok("wolumeny danych odtworzone (seed wykona sie przy starcie api)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def wait_health(remote: Remote, remote_dir: str, api_port: str, max_wait_s: int = 180) -> None:
|
|
|
|
|
step(f"Zdrowie: /health przez port API {api_port} (czekam max {max_wait_s} s)")
|
|
|
|
|
deadline = time.monotonic() + max_wait_s
|
|
|
|
|
while time.monotonic() < deadline:
|
|
|
|
|
res = remote.check(f"curl -fsS http://127.0.0.1:{api_port}/health")
|
|
|
|
|
if res.returncode == 0 and '"ok"' in res.stdout:
|
|
|
|
|
ok("API healthy")
|
|
|
|
|
return
|
|
|
|
|
time.sleep(3)
|
|
|
|
|
remote.exec(f"{compose(remote_dir)} logs --tail 40 api 2>&1", timeout=120)
|
|
|
|
|
die("Weryfikacja /health nieudana — powyzej ostatnie logi api.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def smoke_session(remote: Remote, admin_port: str, email: str, password: str) -> None:
|
|
|
|
|
step("Smoke sesji: login + refresh przez port admina (same-origin)")
|
|
|
|
|
body = f'{{"email":"{email}","password":"{password}"}}'
|
|
|
|
|
login = remote.exec(
|
|
|
|
|
f"""
|
|
|
|
|
curl -s -o /tmp/fitos-smoke-login.json -w '%{{http_code}}' -c /tmp/fitos-smoke.jar \\
|
|
|
|
|
-X POST http://127.0.0.1:{admin_port}/api/v1/auth/login \\
|
|
|
|
|
-H 'Content-Type: application/json' -H 'X-Client: admin' -d '{body}'
|
|
|
|
|
"""
|
|
|
|
|
).strip()
|
|
|
|
|
if login != "200":
|
|
|
|
|
detail = remote.exec("cat /tmp/fitos-smoke-login.json; echo").strip()
|
|
|
|
|
die(
|
|
|
|
|
f"smoke login wrocil {login} zamiast 200: {detail}\n"
|
|
|
|
|
"Jezeli haslo admina zostalo zmienione po seedzie — uzyj --no-smoke."
|
|
|
|
|
)
|
|
|
|
|
refresh = remote.exec(
|
|
|
|
|
f"""
|
|
|
|
|
curl -s -o /tmp/fitos-smoke-refresh.json -w '%{{http_code}}' -b /tmp/fitos-smoke.jar \\
|
|
|
|
|
-X POST http://127.0.0.1:{admin_port}/api/v1/auth/refresh -H 'X-Client: admin'
|
|
|
|
|
"""
|
|
|
|
|
).strip()
|
|
|
|
|
token_ok = remote.check("grep -q accessToken /tmp/fitos-smoke-refresh.json").returncode == 0
|
|
|
|
|
remote.exec("rm -f /tmp/fitos-smoke.jar /tmp/fitos-smoke-login.json /tmp/fitos-smoke-refresh.json")
|
|
|
|
|
if refresh != "200" or not token_ok:
|
|
|
|
|
die(f"smoke refresh wrocil {refresh}, accessToken={token_ok} — sesja NIE dziala (regresja!).")
|
|
|
|
|
ok("login+refresh 200 + nowy accessToken — ten sam origin, ciastko leci")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def summarize(remote: Remote, remote_dir: str, cfg: dict[str, str]) -> None:
|
|
|
|
|
step("docker compose ps + RELEASE")
|
|
|
|
|
print(remote.exec(f"{compose(remote_dir)} ps 2>&1", timeout=60))
|
|
|
|
|
print(remote.exec(f"cat ~/{remote_dir}/RELEASE", timeout=30))
|
2026-10-14 05:07:09 +02:00
|
|
|
# SSH_TARGET bywa "user@host" — w adresach przeglądarki liczy się tylko host
|
|
|
|
|
host = (cfg.get("SSH_TARGET") or "?").split("@")[-1]
|
2026-10-14 04:49:53 +02:00
|
|
|
print("Deploy zakonczony — FitOS (same-origin, API proxywane przez nginx frontow):")
|
|
|
|
|
print(f" App: http://{host}:{cfg['APP_HOST_PORT']}")
|
|
|
|
|
print(f" Admin: http://{host}:{cfg['ADMIN_HOST_PORT']}")
|
|
|
|
|
print(f" API: http://{host}:{cfg['API_HOST_PORT']} (docs: /api/docs poza prod)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- main ------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def main() -> None:
|
|
|
|
|
parser = argparse.ArgumentParser(description="Deploy FitOS z refa gita na staging/prod.")
|
|
|
|
|
parser.add_argument("-e", "--env", required=True, choices=SUPPORTED_ENVS, help="srodowisko deployu")
|
|
|
|
|
parser.add_argument("--ref", default="origin/main", help="ref gita do wystawienia (domyślnie origin/main po fetchu)")
|
|
|
|
|
parser.add_argument("--no-build", action="store_true", help="up -d bez --build (obrazy juz aktualne)")
|
|
|
|
|
parser.add_argument("--no-smoke", action="store_true", help="pomin smoke sesji login+refresh")
|
|
|
|
|
parser.add_argument("--logs", action="store_true", help="na koniec: docker compose logs --tail 60")
|
|
|
|
|
parser.add_argument("--reset-db", action="store_true", help="TYLKO staging: skasuj wolumeny danych (potwierdzenie na zywo)")
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
env_path = DEPLOY_DIR / f".deploy.{args.env}.env"
|
|
|
|
|
if not env_path.is_file():
|
|
|
|
|
die(
|
|
|
|
|
f"Brak pliku {env_path}\n"
|
|
|
|
|
f" Skopiuj deploy/.deploy.{args.env}.env.example -> deploy/.deploy.{args.env}.env i uzupelnij."
|
|
|
|
|
)
|
|
|
|
|
cfg = load_env_file(env_path)
|
|
|
|
|
fill_secrets(cfg, env_path)
|
|
|
|
|
|
|
|
|
|
for key in ("ADMIN_HOST_PORT", "APP_HOST_PORT", "API_HOST_PORT", "DB_HOST_PORT", "PGDATA_VOLUME", "UPLOADS_VOLUME"):
|
|
|
|
|
if not cfg.get(key):
|
|
|
|
|
die(f"Brak {key} w {env_path.name}")
|
|
|
|
|
volumes = [cfg["PGDATA_VOLUME"], cfg["UPLOADS_VOLUME"]]
|
|
|
|
|
remote_dir = cfg.get("REMOTE_DIR") or f"fitos-{args.env}"
|
|
|
|
|
remote = Remote(cfg)
|
|
|
|
|
|
|
|
|
|
if args.reset_db:
|
|
|
|
|
if args.env != "staging":
|
|
|
|
|
die("--reset-db jest dostepne tylko dla srodowiska staging.")
|
|
|
|
|
answer = input(f"Pisz '{args.env}', aby skasowac dane (wolumeny {', '.join(volumes)}) i z seedowac od nowa: ")
|
|
|
|
|
if answer.strip() != args.env:
|
|
|
|
|
die("Przerwano — potwierdzenie niepodane.")
|
|
|
|
|
|
|
|
|
|
tar_path, sha = prepare_archive(args.ref)
|
|
|
|
|
try:
|
|
|
|
|
sync_tree(remote, tar_path, remote_dir, args.env)
|
|
|
|
|
write_release(remote, remote_dir, args.ref, sha)
|
|
|
|
|
write_stack_env(remote, remote_dir, cfg, args.env)
|
|
|
|
|
if not args.no_build:
|
|
|
|
|
stack_build(remote, remote_dir)
|
|
|
|
|
# dopiero teraz zwalniamy porty: kontenery starego projektu -> nowe
|
|
|
|
|
require_volumes(remote, volumes)
|
|
|
|
|
migrate_legacy_project(remote, args.env)
|
|
|
|
|
if args.reset_db:
|
|
|
|
|
reset_db(remote, remote_dir, volumes)
|
|
|
|
|
stack_up(remote, remote_dir)
|
|
|
|
|
wait_health(remote, remote_dir, cfg["API_HOST_PORT"])
|
|
|
|
|
if not args.no_smoke:
|
|
|
|
|
smoke_session(remote, cfg["ADMIN_HOST_PORT"], cfg.get("FITOS_FIRST_ADMIN_EMAIL") or "admin@fitos.local", cfg["FITOS_FIRST_ADMIN_PASSWORD"])
|
|
|
|
|
if args.logs:
|
|
|
|
|
step("Logi stosu (ostatnie 60 linii)")
|
|
|
|
|
print(remote.exec(f"{compose(remote_dir)} logs --tail 60 2>&1", timeout=120))
|
|
|
|
|
summarize(remote, remote_dir, cfg)
|
|
|
|
|
finally:
|
|
|
|
|
tar_path.unlink(missing_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
try:
|
|
|
|
|
main()
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
|
die("przerwano przez uzytkownika")
|