From 30ec4d36d4f6a938031ac252243b5f7c75e042a4 Mon Sep 17 00:00:00 2001 From: Tilumca Date: Wed, 14 Oct 2026 04:49:53 +0200 Subject: [PATCH] =?UTF-8?q?Deploy:=20drzewo=20deploy/=20=E2=80=94=20stos?= =?UTF-8?q?=20parametryzowany=20+=20deploy.py=20z=20refa=20gita=20(same-or?= =?UTF-8?q?igin,=20wolumeny=20external,=20smoke=20sesji;=20remote/deploy.p?= =?UTF-8?q?s1=20oznaczony=20DEPRECATED)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + deploy/.deploy.prod.env.example | 40 +++ deploy/.deploy.staging.env.example | 42 +++ deploy/compose.yml | 91 +++++++ deploy/deploy.ps1 | 4 + deploy/deploy.py | 423 +++++++++++++++++++++++++++++ deploy/deploy.sh | 3 + remote/deploy.ps1 | 5 + 8 files changed, 610 insertions(+) create mode 100644 deploy/.deploy.prod.env.example create mode 100644 deploy/.deploy.staging.env.example create mode 100644 deploy/compose.yml create mode 100644 deploy/deploy.ps1 create mode 100755 deploy/deploy.py create mode 100755 deploy/deploy.sh diff --git a/.gitignore b/.gitignore index f556d3c..480ecd4 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,7 @@ blob-report/ *.tsbuildinfo # sekrety deployu na alt-host (wzorzec: remote/.deploy.env.example) remote/.deploy.env +# sekrety deployu deploy/ (wzorce: deploy/.deploy..env.example) +deploy/.deploy.*.env # lokalne plany sesji Kilo .kilo/plans/ diff --git a/deploy/.deploy.prod.env.example b/deploy/.deploy.prod.env.example new file mode 100644 index 0000000..f49975b --- /dev/null +++ b/deploy/.deploy.prod.env.example @@ -0,0 +1,40 @@ +# Konfiguracja deployu FitOS — PRODUKCJA (założenia, wdrozenie osobno). +# Kopiuj do deploy/.deploy.prod.env i uzupelnij — plik jest w .gitignore, NIE commituj go. +# Zasady: na prod idzie TEN SAM ref co przezyl staging; wolumeny wlasne fitos_prod_*; +# od dnia TLS ustaw COOKIE_SECURE=true (Let's Encrypt/certbot przed nginxem). + +# --- srodowisko (nazwa projektu/kontenerow fitos-) --- +DEPLOY_ENV=prod + +# --- SSH (klucz; ewentualnie SSH_PASSWORD + sshpass w PATH) --- +SSH_TARGET=user@prod.example.com +# SSH_PASSWORD= + +# --- katalog roboczy na hoście (domyslnie fitos-prod) --- +REMOTE_DIR=fitos-prod + +# --- sekrety stosu (zapisywane do ~/fitos-prod/.env na hoście) --- +JWT_ACCESS_SECRET= +JWT_REFRESH_SECRET= +FITOS_FIRST_ADMIN_EMAIL=admin@example.com +FITOS_FIRST_ADMIN_PASSWORD= + +# --- porty hosta (prod: standardowe 9xxx, jezeli serwer nie dzieli ich z niczym) --- +ADMIN_HOST_PORT=9000 +APP_HOST_PORT=9001 +API_HOST_PORT=9002 +DB_HOST_PORT=9543 + +# --- wolumeny danych (EXTERNAL — na prod NIGDY nie dzielic ze stagingiem; +# przy pierwszym deployu utworz recznie: docker volume create ) --- +PGDATA_VOLUME=fitos_prod_pgdata +UPLOADS_VOLUME=fitos_prod_uploads + +# --- strefa czasowa, logi, cookie --- +TZ=Europe/Warsaw +LOG_LEVEL=info +# true od pierwszego wdrozenia za TLS (secure ciastko refresh wymaga HTTPS) +COOKIE_SECURE=true + +# --- AWARYJNIE: dokladne origins ponad same-origin — domyslnie NIE ustawiaj --- +# CORS_EXTRA_ORIGINS= diff --git a/deploy/.deploy.staging.env.example b/deploy/.deploy.staging.env.example new file mode 100644 index 0000000..dfb9891 --- /dev/null +++ b/deploy/.deploy.staging.env.example @@ -0,0 +1,42 @@ +# Konfiguracja deployu FitOS — STAGING (alt-host 192.168.50.127, porty 13xxx). +# Kopiuj do deploy/.deploy.staging.env i uzupelnij — plik jest w .gitignore, NIE commituj go. +# Sekrety JWT/FITOS_FIRST_ADMIN_PASSWORD moga zostac puste — deploy.py wygeneruje +# losowe wartosci i zapisze je z powrotem do tego pliku. + +# --- srodowisko (nazwa projektu/kontenerow fitos-) --- +DEPLOY_ENV=staging + +# --- SSH (klucz; ewentualnie SSH_PASSWORD + sshpass w PATH) --- +SSH_TARGET=homelab +# SSH_TARGET=user@192.168.50.127 +# SSH_PASSWORD= + +# --- katalog roboczy na hoście (w katalogu domowym usera; domyslnie fitos-staging) --- +REMOTE_DIR=fitos-staging + +# --- sekrety stosu (zapisywane do ~/fitos-staging/.env na hoście) --- +JWT_ACCESS_SECRET= +JWT_REFRESH_SECRET= +FITOS_FIRST_ADMIN_EMAIL=admin@fitos.local +FITOS_FIRST_ADMIN_PASSWORD= + +# --- porty hosta (odpowiedniki 9xxx: admin 13000, app 13001, api 13002) --- +ADMIN_HOST_PORT=13000 +APP_HOST_PORT=13001 +API_HOST_PORT=13002 +DB_HOST_PORT=13543 + +# --- wolumeny danych (EXTERNAL — przetrwaja rebuildy; migracja ze starego +# projektu "fitos-alt" = te same wolumeny, zero utraty danych). +# Zweryfikuj dokladne nazwy na hoście: docker volume ls | grep fitos --- +PGDATA_VOLUME=fitos_alt_pgdata +UPLOADS_VOLUME=fitos_alt_uploads + +# --- strefa czasowa, logi, cookie (HTTPS = Secure ciastko) --- +TZ=Europe/Warsaw +LOG_LEVEL=info +COOKIE_SECURE=false + +# --- AWARYJNIE: dokladne origins ponad same-origin (nginx proxyje /api i /health +# w tym samym originie, wiec domyslnie NIE ustawiaj) --- +# CORS_EXTRA_ORIGINS= diff --git a/deploy/compose.yml b/deploy/compose.yml new file mode 100644 index 0000000..ac35e7d --- /dev/null +++ b/deploy/compose.yml @@ -0,0 +1,91 @@ +# FitOS — stos deployowy (staging i prod z jednego pliku). +# Parametryzowany przez --env-file .env generowany przez deploy/deploy.py +# (wzorce: .deploy..env.example). NIE odpalać ręcznie bez tego pliku — +# deploy.py odpowiada za RELEASE, wstepna kontrole wolumenow i smoke sesji. +# +# Same-origin: nginx w app/admin proxyje /api i /health do api:9002 (siec projektu), +# wiec config.js ma pusty apiUrl i zadne CORS nie jest potrzebne. +# Wolumeny danych sa EXTERNAL — przetrwaja usuniecie stosu; tworzy je operator +# (deploy.py celowo zatrzymuje sie, gdy brakuje ktoregokolwiek). +name: fitos-${DEPLOY_ENV:?set DEPLOY_ENV in .env} + +services: + api: + build: ../api + container_name: fitos-api-${DEPLOY_ENV} + ports: + - "${API_HOST_PORT:?set API_HOST_PORT in .env}:9002" + environment: + DATABASE_URL: postgresql://fitos:fitos@db:5432/fitos + PORT: 9002 + NODE_ENV: production + JWT_ACCESS_SECRET: ${JWT_ACCESS_SECRET:?set JWT_ACCESS_SECRET in .env} + JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET:?set JWT_REFRESH_SECRET in .env} + FITOS_FIRST_ADMIN_EMAIL: ${FITOS_FIRST_ADMIN_EMAIL:-} + FITOS_FIRST_ADMIN_PASSWORD: ${FITOS_FIRST_ADMIN_PASSWORD:-} + LOG_LEVEL: ${LOG_LEVEL:-info} + # true tylko gdy front stoi po HTTPS (Secure ciastko refresh) + COOKIE_SECURE: ${COOKIE_SECURE:-false} + # AWARYJNIE: dokladne origins ponad same-origin (domyślnie puste = nepotrzebne) + CORS_EXTRA_ORIGINS: ${CORS_EXTRA_ORIGINS:-} + UPLOAD_DIR: /app/uploads + # Daty treningowe (północ/23:59 dnia) liczone są w strefie procesu — + # kontener musi pracować w strefie użytkowników, nie w UTC. + TZ: ${TZ:-Europe/Warsaw} + volumes: + - uploads:/app/uploads + depends_on: + db: + condition: service_healthy + healthcheck: + test: ["CMD", "wget", "-qO-", "http://localhost:9002/health"] + interval: 30s + timeout: 5s + retries: 5 + start_period: 30s + restart: unless-stopped + + db: + image: postgres:16-alpine + container_name: fitos-db-${DEPLOY_ENV} + ports: + # tylko localhost na hoście — dostęp wyłącznie z sieci compose (DNS "db") + - "127.0.0.1:${DB_HOST_PORT:?set DB_HOST_PORT in .env}:5432" + environment: + POSTGRES_USER: fitos + POSTGRES_PASSWORD: fitos + POSTGRES_DB: fitos + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U fitos -d fitos"] + interval: 10s + timeout: 5s + retries: 5 + restart: unless-stopped + + app: + build: ../app + container_name: fitos-app-${DEPLOY_ENV} + ports: + - "${APP_HOST_PORT:?set APP_HOST_PORT in .env}:9001" + environment: + API_UPSTREAM: api:9002 + restart: unless-stopped + + admin: + build: ../admin + container_name: fitos-admin-${DEPLOY_ENV} + ports: + - "${ADMIN_HOST_PORT:?set ADMIN_HOST_PORT in .env}:9000" + environment: + API_UPSTREAM: api:9002 + restart: unless-stopped + +volumes: + pgdata: + name: ${PGDATA_VOLUME:?set PGDATA_VOLUME in .env} + external: true + uploads: + name: ${UPLOADS_VOLUME:?set UPLOADS_VOLUME in .env} + external: true diff --git a/deploy/deploy.ps1 b/deploy/deploy.ps1 new file mode 100644 index 0000000..a531171 --- /dev/null +++ b/deploy/deploy.ps1 @@ -0,0 +1,4 @@ +# Otoczka deployu FitOS (Windows) — core w Pythonie (deploy.py). +# Wymaga python w PATH (python.org albo `winget install Python.Python.3.12`). +& python "$PSScriptRoot/deploy.py" @args +exit $LASTEXITCODE diff --git a/deploy/deploy.py b/deploy/deploy.py new file mode 100755 index 0000000..8323421 --- /dev/null +++ b/deploy/deploy.py @@ -0,0 +1,423 @@ +#!/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 (wzorce: .deploy..env.example). + +Kroki: git fetch -> git archive (api admin app deploy) -> scp -> na hoście +.swap drzewa ~/fitos- (.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 -------------------------------------------------- + +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-' (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; jezeli to swieze srodowisko," + "\n utworz je swiadomie: docker volume create " + ) + + +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)) + host = cfg.get("SSH_TARGET") or "?" + 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") diff --git a/deploy/deploy.sh b/deploy/deploy.sh new file mode 100755 index 0000000..5c66e8e --- /dev/null +++ b/deploy/deploy.sh @@ -0,0 +1,3 @@ +#!/bin/sh +# Otoczka deployu FitOS — core w Pythonie (deploy.py). +exec python3 "$(dirname "$0")/deploy.py" "$@" diff --git a/remote/deploy.ps1 b/remote/deploy.ps1 index 62c4356..b9bd739 100644 --- a/remote/deploy.ps1 +++ b/remote/deploy.ps1 @@ -1,4 +1,9 @@ <# +.DEPRECATED + PRZESTARZALE — nie rozbudowywac. Zastapione przez deploy/deploy.ps1 (core deploy/deploy.py, + deploy z refa gita, same-origin bez config.js/CORS). Usuniecie po zwalidowaniu deployu + na stagingu nowym stosem (docs/srodowiska.md). Nie uzyc bez swiadomej decyzji. + .SYNOPSIS Deploy FitOS na alternatywne urzadzenie (alt-host 192.168.50.127) - porty 13xxx.