tippspiel2027/tools/deploy_live.py

678 lines
22 KiB
Python
Executable file

#!/usr/bin/env python3
"""
Deploy-Skript für das Livesystem hoschis-tippspiel.de.
Lädt tippspiel/public und tippspiel/src per FTP nach /tippspiel und schreibt
dort die .htaccess mit den Environment-Variablen (SetEnv).
Zugangsdaten werden aus docs/live_credentials.txt gelesen (gitignored).
Wichtig: Standardmäßig werden NUR Dateien hochgeladen. Ein DB-Sync
(lokale tippspiel2027 -> Live-DB, ersetzt alle Live-Tabellen) muss mit
--db-sync ausdrücklich aktiviert werden. Vorher wird ein Backup der Live-DB
angelegt; die Live-Daten seit dem letzten lokalen Import gehen verloren.
Beispiele:
./deploy_live.py # nur Dateien (public/ + src/)
./deploy_live.py --skip-img-upload # Dateien ohne public/img
./deploy_live.py --dry-run # nur prüfen, nichts schreiben
./deploy_live.py --db-sync # zusätzlich Live-DB überschreiben
./deploy_live.py --db-only # nur Live-DB überschreiben
./deploy_live.py --check # nach dem Deploy HTTP-Smoke-Test
"""
import argparse
import io
import os
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
from datetime import datetime
from ftplib import FTP, error_perm
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS_DIR = os.path.join(REPO_ROOT, "tools")
APP_DIR = os.path.join(REPO_ROOT, "tippspiel")
CRED_FILE = os.path.join(REPO_ROOT, "docs", "live_credentials.txt")
DEFAULT_BACKUP_DIR = os.path.expanduser("~/backups/tippspiel-live")
REMOTE_ROOT = "tippspiel"
# Zwischenablage für atomare Uploads: liegt neben public/ und damit ausserhalb
# des Web-Roots - Dateien dort sind während des Uploads nicht abrufbar.
STAGING_DIR = "/%s/.staging" % REMOTE_ROOT
FTP_PORT = 21
DEFAULT_APP_URL = "https://hoschis-tippspiel.de"
# Lokale, migrierte DB (siehe tools/docker-compose.yml)
LOCAL_DB = {
"host": "127.0.0.1",
"port": "3306",
"user": "root",
"password": "root",
"name": "tippspiel2027",
}
OPTIONAL_ENV_PREFIXES = ("APIFOOTBALL_", "SMTP_", "MAIL_")
HTACCESS_ORDER = (
"DB_HOST",
"DB_USER",
"DB_PASS",
"DB_NEW_NAME",
"APP_URL",
"IBAN_KEY",
"APIFOOTBALL_KEY",
"SMTP_HOST",
"SMTP_PORT",
"SMTP_ENCRYPTION",
"SMTP_USER",
"SMTP_PASS",
"MAIL_FROM",
"MAIL_FROM_NAME",
)
FTP_SKIP = {".DS_Store", "Thumbs.db"}
class DeployError(RuntimeError):
pass
def log(message=""):
print(message, flush=True)
def timestamp():
return datetime.now().strftime("%Y-%m-%d_%H%M%S")
def read_credentials(path):
creds = {}
with open(path, "r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
creds[key.strip()] = value.strip()
return creds
def live_connection(creds):
return {
"host": creds.get("db_host") or creds["ftp_url"],
"port": creds.get("db_port") or "3306",
"user": creds.get("mysql_user") or creds["mysql_db"],
"password": creds["mysql_pw"],
"name": creds["mysql_db"],
}
def local_iban_key():
"""Lokaler Schlüssel (tools/.env), damit Live den lokalen Dump lesen kann."""
env_key = os.environ.get("IBAN_KEY")
if env_key:
return env_key
try:
with open(os.path.join(TOOLS_DIR, ".env"), "r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if line.startswith("IBAN_KEY="):
return line.split("=", 1)[1].strip().strip('"').strip("'")
except OSError:
pass
return None
def htaccess_value(value):
"""SetEnv-Werte quoten: Leerzeichen (z. B. MAIL_FROM_NAME) führen sonst zu 500."""
escaped = str(value).replace("\\", "\\\\").replace('"', '\\"')
return '"%s"' % escaped
def build_htaccess(creds, app_url):
values = {
"DB_HOST": creds.get("db_host") or "localhost",
"DB_USER": creds.get("mysql_user") or creds["mysql_db"],
"DB_PASS": creds["mysql_pw"],
"DB_NEW_NAME": creds["mysql_db"],
"APP_URL": app_url,
"IBAN_KEY": creds.get("iban_key", ""),
}
for key, value in creds.items():
upper = key.upper()
if upper.startswith(OPTIONAL_ENV_PREFIXES) and value:
values[upper] = value
lines = [
"# Auto-generiert von deploy_live.py - NICHT manuell editieren",
"Options -Indexes",
"",
"<IfModule mod_rewrite.c>",
"RewriteEngine On",
"RewriteCond %{HTTPS} off",
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]",
"</IfModule>",
"",
]
for name in HTACCESS_ORDER:
if values.get(name):
lines.append("SetEnv %s %s" % (name, htaccess_value(values[name])))
lines.append("")
return "\n".join(lines), values
def run(cmd, env=None, input_data=None):
proc = subprocess.run(
cmd,
env=env,
input=input_data,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if proc.returncode != 0:
raise DeployError(
"Befehl fehlgeschlagen: %s\n%s"
% (" ".join(cmd), proc.stderr.decode("utf-8", "replace").strip())
)
return proc.stdout
def mysql_env(conn):
return dict(os.environ, MYSQL_PWD=str(conn["password"]))
def mysql_cmd(conn, db=True):
cmd = [
"mysql",
"--connect-timeout=15",
"--default-character-set=utf8mb4",
"-h", str(conn["host"]),
"-P", str(conn["port"]),
"-u", str(conn["user"]),
]
if db:
cmd.append(str(conn["name"]))
return cmd
def mysql_query(conn, sql):
return run(mysql_cmd(conn) + ["-N", "-B", "-e", sql], env=mysql_env(conn)).decode(
"utf-8", "replace"
)
def mysqldump_cmd(conn, extra=None):
return [
"mysqldump",
"--no-tablespaces",
"--column-statistics=0",
"--single-transaction",
"--quick",
"--default-character-set=utf8mb4",
"-h", str(conn["host"]),
"-P", str(conn["port"]),
"-u", str(conn["user"]),
] + (extra or []) + [str(conn["name"])]
def dump_database(conn, path, extra=None):
with open(path, "wb") as out:
proc = subprocess.run(
mysqldump_cmd(conn, extra),
env=mysql_env(conn),
stdin=subprocess.DEVNULL,
stdout=out,
stderr=subprocess.PIPE,
)
if proc.returncode != 0:
raise DeployError(
"mysqldump für '%s' fehlgeschlagen:\n%s"
% (conn["name"], proc.stderr.decode("utf-8", "replace").strip())
)
if os.path.getsize(path) == 0:
raise DeployError("Dump von '%s' ist leer: %s" % (conn["name"], path))
os.chmod(path, 0o600)
return path
def list_tables(conn):
out = mysql_query(conn, "SHOW TABLES;")
return sorted(line.strip() for line in out.splitlines() if line.strip())
def table_counts(conn, tables):
if not tables:
return {}
sql = " UNION ALL ".join(
"SELECT '%s', COUNT(*) FROM `%s`" % (t, t) for t in tables
)
out = mysql_query(conn, sql + ";")
counts = {}
for line in out.splitlines():
if not line.strip():
continue
name, _, value = line.partition("\t")
counts[name.strip()] = int(value.strip() or 0)
return counts
def account_stats(conn):
"""Anzahl gepflegter Kontodaten, um Datenverlust beim DB-Sync zu erkennen."""
try:
row = mysql_query(
conn,
"SELECT COALESCE(SUM(iban IS NOT NULL AND iban <> ''), 0), "
"COALESCE(SUM(mobile IS NOT NULL AND mobile <> ''), 0), "
"COALESCE(SUM(paypal IS NOT NULL AND paypal <> ''), 0), "
"COALESCE(DATE_FORMAT(MAX(updated_at), '%Y-%m-%d %H:%i'), '-') "
"FROM users;",
).strip()
except DeployError:
return None
parts = row.split("\t")
if len(parts) < 4:
return None
return {
"iban": int(parts[0] or 0),
"mobile": int(parts[1] or 0),
"paypal": int(parts[2] or 0),
"updated": parts[3],
}
def warn_about_account_data(live):
local = account_stats(LOCAL_DB)
remote = account_stats(live)
if not local or not remote:
return
log(" Kontodaten lokal: IBAN %d, Handy %d, PayPal %d (Stand %s)"
% (local["iban"], local["mobile"], local["paypal"], local["updated"]))
log(" Kontodaten live: IBAN %d, Handy %d, PayPal %d (Stand %s)"
% (remote["iban"], remote["mobile"], remote["paypal"], remote["updated"]))
if (remote["iban"] > local["iban"] or remote["mobile"] > local["mobile"]
or remote["paypal"] > local["paypal"]):
log(" WARNUNG: Live enthält mehr Kontodaten als die lokale DB.")
log(" Ein DB-Sync würde diese Werte überschreiben.")
def ensure_private_dir(path):
os.makedirs(path, mode=0o700, exist_ok=True)
try:
os.chmod(path, 0o700)
except OSError:
pass
def sync_database(live, backup_dir, dry_run=False):
log("")
log("== DB-Sync: lokale '%s' -> Live '%s' ==" % (LOCAL_DB["name"], live["name"]))
try:
local_tables = list_tables(LOCAL_DB)
except DeployError:
raise DeployError(
"Lokale DB nicht erreichbar (%s@%s:%s). Läuft Docker? "
"'cd tools && docker compose up -d'"
% (LOCAL_DB["user"], LOCAL_DB["host"], LOCAL_DB["port"])
)
if not local_tables:
raise DeployError("Lokale DB '%s' enthält keine Tabellen." % LOCAL_DB["name"])
local_counts = table_counts(LOCAL_DB, local_tables)
if not local_counts.get("users"):
raise DeployError("Lokale DB enthält keine Users - falsche Datenbank?")
existing = list_tables(live)
live_counts = table_counts(live, existing)
log(" Lokal: %d Tabellen, %d Users, %d Tipps"
% (len(local_tables), local_counts.get("users", 0), local_counts.get("tipps", 0)))
log(" Live: %d Tabellen, %d Users, %d Tipps"
% (len(existing), live_counts.get("users", 0), live_counts.get("tipps", 0)))
warn_about_account_data(live)
if dry_run:
log(" [Dry-Run] Live-Tabellen würden gesichert, gelöscht und ersetzt.")
return
if existing:
ensure_private_dir(backup_dir)
backup_path = os.path.join(
backup_dir, "live_%s_%s.sql" % (live["name"], timestamp())
)
log(" Sichere Live-DB nach %s ..." % backup_path)
dump_database(live, backup_path)
log(" Backup OK, %.1f MB" % (os.path.getsize(backup_path) / 1024 / 1024))
fd, dump_path = tempfile.mkstemp(prefix="tippspiel2027_", suffix=".sql")
os.close(fd)
try:
log(" Dumpe lokale '%s' ..." % LOCAL_DB["name"])
dump_database(LOCAL_DB, dump_path)
if existing:
log(" Lösche %d vorhandene Live-Tabellen ..." % len(existing))
drop_sql = (
"SET FOREIGN_KEY_CHECKS=0; "
+ " ".join("DROP TABLE IF EXISTS `%s`;" % t for t in existing)
+ " SET FOREIGN_KEY_CHECKS=1;"
)
mysql_query(live, drop_sql)
log(" Spiele %.1f MB in '%s' ein ..."
% (os.path.getsize(dump_path) / 1024 / 1024, live["name"]))
with open(dump_path, "rb") as handle:
dump_data = handle.read()
run(mysql_cmd(live), env=mysql_env(live), input_data=dump_data)
finally:
if os.path.exists(dump_path):
os.unlink(dump_path)
remote_tables = list_tables(live)
missing = sorted(set(local_tables) - set(remote_tables))
if missing:
raise DeployError("Nach dem Import fehlen Live-Tabellen: %s" % ", ".join(missing))
remote_counts = table_counts(live, remote_tables)
mismatches = [
"%s (lokal %d, live %d)" % (t, local_counts.get(t, 0), remote_counts.get(t, 0))
for t in local_tables
if local_counts.get(t, 0) != remote_counts.get(t, 0)
]
if mismatches:
raise DeployError("Zeilenanzahl weicht ab: %s" % ", ".join(mismatches))
log(" OK, %d Tabellen übernommen und verifiziert." % len(remote_tables))
def mkd_ignore_exists(ftp, name):
try:
ftp.mkd(name)
except error_perm as exc:
if not str(exc.args[0]).startswith("550"):
raise
def staging_path(remote_path):
"""Zwischenablage ausserhalb des Web-Roots (nicht per Browser erreichbar)."""
name = remote_path.strip("/").replace("/", "__")
return "%s/%s.tmp" % (STAGING_DIR, name)
def store_atomic(ftp, remote_path, source):
"""Lädt eine Datei hoch und benennt sie erst dann an ihren Platz um.
Ein direktes STOR in die Zieldatei trunkiert sie zuerst; ein Request in
genau diesem Moment könnte eine halb geschriebene Datei lesen (bei
index.php: Parse-Fehler, also 500 für den Besucher). rename() ist auf
demselben Dateisystem atomar - die Datei ist entweder vollständig alt
oder vollständig neu.
`source` ist ein lokaler Pfad oder ein bereits geöffnetes Dateiobjekt.
"""
tmp_path = staging_path(remote_path)
if hasattr(source, "read"):
ftp.storbinary("STOR " + tmp_path, source)
else:
with open(source, "rb") as handle:
ftp.storbinary("STOR " + tmp_path, handle)
try:
ftp.rename(tmp_path, remote_path)
except Exception:
try:
ftp.delete(tmp_path)
except error_perm:
pass
raise
def upload_dir(ftp, local_dir, remote_dir, skip=None):
mkd_ignore_exists(ftp, remote_dir)
skip = skip or set()
count = 0
for name in sorted(os.listdir(local_dir)):
if name in skip or name in FTP_SKIP:
continue
local_path = os.path.join(local_dir, name)
remote_path = remote_dir.rstrip("/") + "/" + name
if os.path.isfile(local_path):
store_atomic(ftp, remote_path, local_path)
count += 1
elif os.path.isdir(local_path):
count += upload_dir(ftp, local_path, remote_path, skip)
return count
def smoke_test(app_url):
base = app_url.rstrip("/")
log("")
log("== Smoke-Test gegen %s ==" % base)
failures = []
def fetch(path):
request = urllib.request.Request(
base + path, headers={"User-Agent": "deploy_live/1.0"}
)
with urllib.request.urlopen(request, timeout=20) as response:
return response.status, response.geturl(), response.read(300000)
try:
status, final_url, body = fetch("/")
text = body.decode("utf-8", "replace")
if status != 200:
failures.append("App: HTTP %d" % status)
elif "page=login" not in text:
failures.append("App: Login-Seite nicht erkannt")
else:
log(" [ok] App/Login erreichbar (%s)" % final_url)
except Exception as exc:
failures.append("App: %s: %s" % (type(exc).__name__, exc))
for path, label in (("/css/style.css", "CSS"), ("/manifest.json", "Manifest")):
try:
status, _, body = fetch(path)
if status == 200 and body:
log(" [ok] %s erreichbar (%d Bytes)" % (label, len(body)))
else:
failures.append("%s: HTTP %d oder leer" % (label, status))
except Exception as exc:
failures.append("%s: %s" % (label, exc))
for message in failures:
log(" [FEHLER] %s" % message)
return not failures
def parse_args():
parser = argparse.ArgumentParser(
description="Deploy auf das Livesystem hoschis-tippspiel.de "
"(FTP-Upload von public/ und src/; DB-Sync nur mit --db-sync).",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="Beispiele:\n"
" %(prog)s\n"
" %(prog)s --skip-img-upload\n"
" %(prog)s --dry-run\n"
" %(prog)s --db-sync\n"
" %(prog)s --db-only\n",
)
parser.add_argument("--db-sync", action="store_true",
help="Live-DB mit der lokalen DB überschreiben (destruktiv, mit Backup)")
parser.add_argument("--db-only", action="store_true",
help="nur Live-DB überschreiben, keine Dateien hochladen")
parser.add_argument("--skip-db-import", action="store_true",
help="DB-Sync überspringen (Standard bei Live, nur zur Klarheit)")
parser.add_argument("--skip-img-upload", action="store_true",
help="public/img/ nicht hochladen")
parser.add_argument("--yes", action="store_true",
help="ohne Rückfrage ausführen (nur mit --db-sync nötig)")
parser.add_argument("--dry-run", action="store_true",
help="nur prüfen (Zugänge, Tabellen, FTP), nichts schreiben")
parser.add_argument("--backup-dir", default=os.environ.get("BACKUP_DIR", DEFAULT_BACKUP_DIR),
help="Verzeichnis für Live-DB-Backups (Default: %(default)s)")
parser.add_argument("--app-url", default=os.environ.get("APP_URL", DEFAULT_APP_URL),
help="APP_URL für die .htaccess (Default: %(default)s)")
parser.add_argument("--check", action="store_true",
help="nach dem Deploy einen HTTP-Smoke-Test ausführen")
return parser.parse_args()
def main():
args = parse_args()
if args.db_sync and args.skip_db_import:
log("Fehler: --db-sync und --skip-db-import widersprechen sich.")
return 1
if args.db_only:
args.db_sync = True
if not os.path.isfile(CRED_FILE):
log("Fehler: Credentials nicht gefunden: %s" % CRED_FILE)
return 1
creds = read_credentials(CRED_FILE)
missing = [key for key in ("ftp_url", "ftp_user", "ftp_pw", "mysql_db", "mysql_pw")
if not creds.get(key)]
if missing:
log("Fehler: Fehlende Einträge in %s: %s" % (CRED_FILE, ", ".join(missing)))
return 1
if not creds.get("iban_key"):
log("Fehler: 'iban_key' fehlt in %s. Ohne Schlüssel wären IBANs live nicht lesbar."
% CRED_FILE)
return 1
local_key = local_iban_key()
if local_key and local_key != creds["iban_key"]:
log("Fehler: lokaler IBAN_KEY (tools/.env) weicht von 'iban_key' in %s ab."
% CRED_FILE)
return 1
live = live_connection(creds)
htaccess, written_env = build_htaccess(creds, args.app_url)
log("Ziel:")
log(" FTP: %s@%s -> /%s" % (creds["ftp_user"], creds["ftp_url"], REMOTE_ROOT))
log(" DB: %s@%s/%s" % (live["user"], live["host"], live["name"]))
log(" App: %s" % args.app_url)
log(" Modus: %s" % (
"nur DB" if args.db_only else
"DB + Dateien" if args.db_sync else
"nur Dateien (kein DB-Sync)"
))
log("")
if args.dry_run:
log("== Dry-Run: es wird nichts geschrieben ==")
if args.db_sync:
try:
sync_database(live, args.backup_dir, dry_run=True)
except DeployError as exc:
log("[FEHLER] %s" % exc)
else:
log("[plan] DB-Sync übersprungen (Standard). Mit --db-sync aktivierbar.")
try:
ftp = FTP()
ftp.connect(creds["ftp_url"], FTP_PORT, timeout=30)
ftp.login(creds["ftp_user"], creds["ftp_pw"])
entries = [e for e in ftp.nlst() if e not in (".", "..")]
log("[ok] FTP-Login erfolgreich, Root: %s" % ", ".join(sorted(entries)))
ftp.quit()
except Exception as exc:
log("[FEHLER] FTP-Login fehlgeschlagen: %s" % exc)
return 0
if args.db_sync:
log("ACHTUNG: Die Live-DB wird vollständig durch die lokale DB ersetzt.")
log(" Daten, die seit dem letzten lokalen Import live entstanden sind,")
log(" gehen verloren. Vorher wird ein Backup angelegt.")
warn_about_account_data(live)
if not args.yes:
answer = input("Zum Fortfahren 'JA' eingeben: ").strip()
if answer != "JA":
log("Abgebrochen.")
return 1
try:
sync_database(live, args.backup_dir)
except DeployError as exc:
log("FEHLER: %s" % exc)
return 1
if args.db_only:
log("")
log("Fertig (nur DB).")
if args.check:
return 0 if smoke_test(args.app_url) else 1
return 0
try:
ftp = FTP()
ftp.connect(creds["ftp_url"], FTP_PORT, timeout=60)
try:
ftp.login(creds["ftp_user"], creds["ftp_pw"])
mkd_ignore_exists(ftp, REMOTE_ROOT)
mkd_ignore_exists(ftp, STAGING_DIR)
for sub in ("public", "src"):
local_sub = os.path.join(APP_DIR, sub)
if not os.path.isdir(local_sub):
raise DeployError("Lokales Verzeichnis fehlt: %s" % local_sub)
log("")
log("== Lade %s/ hoch ==" % sub)
skip = {"img"} if (sub == "public" and args.skip_img_upload) else None
uploaded = upload_dir(
ftp,
local_sub,
"/%s/%s" % (REMOTE_ROOT, sub),
skip=skip,
)
log(" %d Dateien hochgeladen." % uploaded)
log("")
log("== Schreibe public/.htaccess ==")
store_atomic(
ftp,
"/%s/public/.htaccess" % REMOTE_ROOT,
io.BytesIO(htaccess.encode("utf-8")),
)
# Zwischenablage nur entfernen, wenn sie leer ist (rmd schlaegt
# sonst fehl - Reste eines abgebrochenen Uploads bleiben liegen).
try:
ftp.rmd(STAGING_DIR)
except error_perm:
pass
ftp.quit()
except Exception:
try:
ftp.close()
except Exception:
pass
raise
except DeployError as exc:
log("FEHLER: %s" % exc)
return 1
except Exception as exc:
log("FEHLER beim FTP-Upload: %s: %s" % (type(exc).__name__, exc))
return 1
log("")
log("Fertig.")
log(" App: https://%s (FTP-Ordner /%s)" % (creds["ftp_url"], REMOTE_ROOT))
log(" .htaccess liegt in /%s/public/.htaccess" % REMOTE_ROOT)
if "APIFOOTBALL_KEY" not in written_env:
log(" Hinweis: Kein APIFOOTBALL_KEY gesetzt.")
if "SMTP_HOST" not in written_env:
log(" Hinweis: Kein SMTP_HOST gesetzt - Mailversand bleibt deaktiviert.")
if args.check:
return 0 if smoke_test(args.app_url) else 1
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)