...
This commit is contained in:
parent
d388a11905
commit
04f1df5abc
8 changed files with 687 additions and 1275 deletions
Binary file not shown.
635
tools/deploy_live.py
Executable file
635
tools/deploy_live.py
Executable file
|
|
@ -0,0 +1,635 @@
|
|||
#!/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"
|
||||
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 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)
|
||||
if os.path.isfile(local_path):
|
||||
with open(local_path, "rb") as handle:
|
||||
ftp.storbinary("STOR " + name, handle)
|
||||
count += 1
|
||||
elif os.path.isdir(local_path):
|
||||
mkd_ignore_exists(ftp, name)
|
||||
ftp.cwd(name)
|
||||
count += upload_dir(ftp, local_path, remote_dir + "/" + name)
|
||||
ftp.cwd("..")
|
||||
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 "Datenbankverbindung fehlgeschlagen" in text:
|
||||
failures.append("App: DB-Verbindung fehlgeschlagen")
|
||||
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)
|
||||
ftp.cwd(REMOTE_ROOT)
|
||||
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)
|
||||
mkd_ignore_exists(ftp, sub)
|
||||
ftp.cwd(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)
|
||||
ftp.cwd("..")
|
||||
|
||||
log("")
|
||||
log("== Schreibe public/.htaccess ==")
|
||||
ftp.cwd("public")
|
||||
ftp.storbinary("STOR .htaccess", io.BytesIO(htaccess.encode("utf-8")))
|
||||
ftp.cwd("..")
|
||||
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)
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Deploy-Skript für das Testsystem tippspiel.programmschmiede.de.
|
||||
|
||||
Lädt das Projekt (tippspiel/public und tippspiel/src) per FTP auf den
|
||||
Testsystem-Server hoch und erzeugt dabei eine .htaccess mit den nötigen
|
||||
Environment-Variablen (SetEnv) im public/-Verzeichnis.
|
||||
|
||||
Zugangsdaten werden aus docs/testsystem_credentials.txt gelesen.
|
||||
Achtung: Zugangsdaten landen als SetEnv in der .htaccess auf dem Server.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from ftplib import FTP, error_perm
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CRED_FILE = os.path.join(REPO_ROOT, "docs", "testsystem_credentials.txt")
|
||||
APP_DIR = os.path.join(REPO_ROOT, "tippspiel")
|
||||
|
||||
FTP_HOST = "programmschmiede.de"
|
||||
FTP_PORT = 21
|
||||
REMOTE_ROOT = "tippspiel.programmschmiede.de"
|
||||
|
||||
# Konfiguration des Testsystems (falls nicht in den Credentials vorhanden)
|
||||
DB_HOST = "localhost"
|
||||
DB_USER = "d0489c69"
|
||||
APP_URL = "https://tippspiel.programmschmiede.de"
|
||||
|
||||
# Quelle für den DB-Sync: lokale, bereits migrierte Datenbank (via Docker)
|
||||
LOCAL_DB_HOST = "127.0.0.1"
|
||||
LOCAL_DB_PORT = "3306"
|
||||
LOCAL_DB_USER = "root"
|
||||
LOCAL_DB_PASS = "root"
|
||||
LOCAL_DB_NAME = "tippspiel2027"
|
||||
|
||||
# Entfernte DB, in die der Dump eingespielt wird
|
||||
REMOTE_DB_HOST = "programmschmiede.de"
|
||||
REMOTE_DB_PORT = "3306"
|
||||
|
||||
|
||||
def read_credentials(path):
|
||||
creds = {}
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
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 build_htaccess(creds):
|
||||
return "\n".join(
|
||||
[
|
||||
"# Auto-generiert von deploy_test.py - NICHT manuell editieren",
|
||||
"Options -Indexes",
|
||||
"",
|
||||
"RewriteEngine On",
|
||||
"RewriteCond %{HTTPS} off",
|
||||
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]",
|
||||
"",
|
||||
"SetEnv DB_HOST " + DB_HOST,
|
||||
"SetEnv DB_USER " + DB_USER,
|
||||
"SetEnv DB_PASS " + creds["mysql_pw"],
|
||||
"SetEnv DB_NEW_NAME " + creds["mysql_db"],
|
||||
"SetEnv APP_URL " + APP_URL,
|
||||
"SetEnv IBAN_KEY " + creds.get("iban_key", ""),
|
||||
"SetEnv APIFOOTBALL_KEY " + creds.get("apifootball_key", ""),
|
||||
"",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def run(cmd, env=None, input_data=None):
|
||||
"""Führt einen Befehl aus und gibt bei Fehlern eine verständliche Meldung aus."""
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
env=env,
|
||||
input=input_data,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(
|
||||
"Befehl fehlgeschlagen: %s\n%s" % (" ".join(cmd), proc.stderr.decode("utf-8", "replace"))
|
||||
)
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def sync_database(creds):
|
||||
"""Dumpt die lokale migrierte DB und spielt sie in die entfernte Test-DB ein."""
|
||||
remote_db = creds["mysql_db"]
|
||||
remote_pw = creds["mysql_pw"]
|
||||
|
||||
print("== DB-Sync: dumpe lokale '%s' ==" % LOCAL_DB_NAME)
|
||||
dump_env = dict(os.environ, MYSQL_PWD=LOCAL_DB_PASS)
|
||||
dump = run(
|
||||
[
|
||||
"mysqldump",
|
||||
"-h", LOCAL_DB_HOST, "-P", LOCAL_DB_PORT,
|
||||
"-u", LOCAL_DB_USER,
|
||||
"--no-tablespaces", "--column-statistics=0",
|
||||
"--no-create-db",
|
||||
LOCAL_DB_NAME,
|
||||
],
|
||||
env=dump_env,
|
||||
)
|
||||
|
||||
print("== DB-Sync: leere entfernte '%s' ==" % remote_db)
|
||||
remote_env = dict(os.environ, MYSQL_PWD=remote_pw)
|
||||
|
||||
# Alle vorhandenen Tabellen ermitteln und droppen
|
||||
tables_out = run(
|
||||
[
|
||||
"mysql",
|
||||
"-h", REMOTE_DB_HOST, "-P", REMOTE_DB_PORT,
|
||||
"-u", DB_USER, remote_db,
|
||||
"-N", "-e",
|
||||
"SELECT table_name FROM information_schema.tables WHERE table_schema='%s';" % remote_db,
|
||||
],
|
||||
env=remote_env,
|
||||
)
|
||||
tables = [t.strip() for t in tables_out.decode("utf-8", "replace").splitlines() if t.strip()]
|
||||
if tables:
|
||||
drop_sql = "SET FOREIGN_KEY_CHECKS=0; " + " ".join(
|
||||
"DROP TABLE IF EXISTS `%s`;" % t for t in tables
|
||||
) + " SET FOREIGN_KEY_CHECKS=1;"
|
||||
run(
|
||||
[
|
||||
"mysql",
|
||||
"-h", REMOTE_DB_HOST, "-P", REMOTE_DB_PORT,
|
||||
"-u", DB_USER, remote_db,
|
||||
"-e", drop_sql,
|
||||
],
|
||||
env=remote_env,
|
||||
)
|
||||
print(" %d Tabellen gelöscht." % len(tables))
|
||||
else:
|
||||
print(" keine Tabellen vorhanden.")
|
||||
|
||||
print("== DB-Sync: spiele Dump in '%s' ein ==" % remote_db)
|
||||
with tempfile.NamedTemporaryFile("wb", delete=False, suffix=".sql") as tmp:
|
||||
tmp.write(dump)
|
||||
dump_path = tmp.name
|
||||
try:
|
||||
with open(dump_path, "rb") as f:
|
||||
run(
|
||||
[
|
||||
"mysql",
|
||||
"-h", REMOTE_DB_HOST, "-P", REMOTE_DB_PORT,
|
||||
"-u", DB_USER, remote_db,
|
||||
],
|
||||
env=remote_env,
|
||||
input_data=f.read(),
|
||||
)
|
||||
finally:
|
||||
os.unlink(dump_path)
|
||||
|
||||
|
||||
def mkd_ignore_exists(ftp, name):
|
||||
try:
|
||||
ftp.mkd(name)
|
||||
except error_perm as e:
|
||||
if not e.args[0].startswith("550"):
|
||||
raise
|
||||
|
||||
|
||||
def upload_dir(ftp, local_dir, remote_dir, skip=None):
|
||||
mkd_ignore_exists(ftp, remote_dir)
|
||||
skip = skip or set()
|
||||
for name in sorted(os.listdir(local_dir)):
|
||||
if name in skip:
|
||||
print("SKIP", remote_dir + "/" + name)
|
||||
continue
|
||||
local_path = os.path.join(local_dir, name)
|
||||
if os.path.isfile(local_path):
|
||||
print("STOR", remote_dir + "/" + name)
|
||||
with open(local_path, "rb") as f:
|
||||
ftp.storbinary("STOR " + name, f)
|
||||
elif os.path.isdir(local_path):
|
||||
print("DIR ", remote_dir + "/" + name)
|
||||
mkd_ignore_exists(ftp, name)
|
||||
ftp.cwd(name)
|
||||
upload_dir(ftp, local_path, remote_dir + "/" + name)
|
||||
ftp.cwd("..")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Deploy auf das Testsystem tippspiel.programmschmiede.de "
|
||||
"(DB-Sync + FTP-Upload von public/ und src/).",
|
||||
epilog="Kombinierbar, z.B. --db-only --skip-img-upload für reine DB-Syncs ohne Bilder.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-db-import",
|
||||
action="store_true",
|
||||
help="DB-Sync überspringen (keine Daten in die entfernte DB einspielen).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--db-only",
|
||||
action="store_true",
|
||||
help="Nur den DB-Sync ausführen, ohne Dateien per FTP hochzuladen.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-img-upload",
|
||||
action="store_true",
|
||||
help="public/img/ nicht hochladen (Logos, Flaggen, Icons).",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.isfile(CRED_FILE):
|
||||
print("Fehler: Credentials nicht gefunden:", CRED_FILE, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
creds = read_credentials(CRED_FILE)
|
||||
for key in ("ftp_user", "ftp_pw", "mysql_db", "mysql_pw"):
|
||||
if key not in creds:
|
||||
print("Fehler: Fehlender Eintrag '%s' in %s" % (key, CRED_FILE), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
htaccess = build_htaccess(creds)
|
||||
|
||||
if args.skip_db_import:
|
||||
print("== DB-Sync übersprungen (--skip-db-import) ==")
|
||||
else:
|
||||
sync_database(creds)
|
||||
|
||||
if args.db_only:
|
||||
print("\nDB-Sync abgeschlossen (ohne Upload) ->", APP_URL)
|
||||
return
|
||||
|
||||
ftp = FTP()
|
||||
ftp.connect(FTP_HOST, FTP_PORT)
|
||||
ftp.login(creds["ftp_user"], creds["ftp_pw"])
|
||||
|
||||
mkd_ignore_exists(ftp, REMOTE_ROOT)
|
||||
ftp.cwd(REMOTE_ROOT)
|
||||
|
||||
for sub in ("public", "src"):
|
||||
local_sub = os.path.join(APP_DIR, sub)
|
||||
if not os.path.isdir(local_sub):
|
||||
print("Fehler: Verzeichnis fehlt:", local_sub, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print("== Lade", sub, "hoch ==")
|
||||
mkd_ignore_exists(ftp, sub)
|
||||
ftp.cwd(sub)
|
||||
skip = {"img"} if (sub == "public" and args.skip_img_upload) else None
|
||||
upload_dir(ftp, local_sub, REMOTE_ROOT + "/" + sub, skip=skip)
|
||||
ftp.cwd("..")
|
||||
|
||||
print("== Schreibe .htaccess in public/ ==")
|
||||
ftp.cwd("public")
|
||||
ftp.storbinary("STOR .htaccess", io.BytesIO(htaccess.encode("utf-8")))
|
||||
ftp.cwd("..")
|
||||
|
||||
ftp.quit()
|
||||
print("\nDeployment abgeschlossen ->", APP_URL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Importiert den neuesten Live-Dump des Legacy-Projekts in die lokale Test-DB
|
||||
# und migriert ihn anschließend in tippspiel2027 (import.php).
|
||||
#
|
||||
# Ablauf:
|
||||
# 1. Colima (Docker-Daemon) starten, falls noch nicht aktiv
|
||||
# 2. Neuesten Dump finden (/home/torsten/repos/tippspiel/tools/pfosten*.sql)
|
||||
# 3. Container starten und auf die DB warten
|
||||
# 4. Legacy-DB "tippspiel_legacy" droppen und neu anlegen
|
||||
# 5. Dump in "tippspiel_legacy" einspielen
|
||||
# 6. import.php ausführen (befüllt tippspiel2027 von scratch)
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
DUMP_DIR="${DUMP_DIR:-/home/torsten/repos/tippspiel/tools}"
|
||||
LEGACY_DB="${DB_OLD_NAME:-tippspiel_legacy}"
|
||||
|
||||
DUMP="${DUMP:-$(ls -1 "$DUMP_DIR"/pfosten*.sql | tail -1)}"
|
||||
if [[ -z "$DUMP" ]]; then
|
||||
echo "Fehler: Kein Dump (pfosten*.sql) in $DUMP_DIR gefunden." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Verwende Dump: $DUMP"
|
||||
|
||||
if command -v colima >/dev/null 2>&1 && ! colima status >/dev/null 2>&1; then
|
||||
echo "Colima ist nicht aktiv, starte es..."
|
||||
colima start
|
||||
fi
|
||||
|
||||
cd "$SCRIPT_DIR"
|
||||
docker compose up -d
|
||||
|
||||
echo "Warte auf die Datenbank..."
|
||||
for _ in $(seq 1 60); do
|
||||
if docker compose exec -T db mysql -uroot -proot -e "SELECT 1;" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
docker compose exec -T db mysql -uroot -proot -e "SELECT 1;" >/dev/null
|
||||
|
||||
echo "Lege Legacy-DB '$LEGACY_DB' neu an..."
|
||||
docker compose exec -T db mysql -uroot -proot \
|
||||
-e "DROP DATABASE IF EXISTS \`$LEGACY_DB\`; CREATE DATABASE \`$LEGACY_DB\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
|
||||
|
||||
echo "Spiele Dump in '$LEGACY_DB' ein..."
|
||||
docker exec -i "$(docker compose ps -q db)" mysql -uroot -proot "$LEGACY_DB" < "$DUMP"
|
||||
|
||||
echo "Führe DB-Import aus (tippspiel2027)..."
|
||||
docker compose exec -T app php import.php
|
||||
|
||||
echo ""
|
||||
echo "Fertig. Öffne die Anwendung im Browser: http://localhost:8080"
|
||||
|
|
@ -1,790 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Go-Live: aktuellen Legacy-Live-Dump laden, lokal migrieren und ins Livesystem
|
||||
(FTP-Ordner "tippspiel") ausrollen.
|
||||
|
||||
Ablauf (wie import_from_dump.sh + deploy_test.py, nur mit Live-Zielen):
|
||||
|
||||
1. Dump der Legacy-Live-DB per mysqldump nach <dump-dir>/pfosten_<ts>.sql
|
||||
2. import_from_dump.sh: Dump in die lokale Docker-DB "tippspiel_legacy"
|
||||
einspielen und mit import.php nach "tippspiel2027" migrieren
|
||||
3. Lokale "tippspiel2027" dumpen und in die Live-DB aus
|
||||
docs/live_credentials.txt einspielen (vorher Backup der Zieltabelle,
|
||||
danach werden die vorhandenen Tabellen gedroppt)
|
||||
4. tippspiel/public und tippspiel/src per FTP nach /tippspiel hochladen
|
||||
und dort die .htaccess mit den Live-Env-Variablen schreiben
|
||||
|
||||
Zugangsdaten:
|
||||
- Live-FTP + Live-DB: docs/live_credentials.txt
|
||||
- Legacy-Live-DB (Quelle): wie tools/sync_live_to_test.sh, per Env
|
||||
LEGACY_HOST / LEGACY_USER / LEGACY_PASS / LEGACY_DB überschreibbar
|
||||
|
||||
Beispiele:
|
||||
./live_migration.py --dry-run # nur prüfen, nichts schreiben
|
||||
./live_migration.py # kompletter Go-Live
|
||||
./live_migration.py --db-only # nur DB, keine Dateien
|
||||
./live_migration.py --skip-db-import # nur Dateien neu hochladen
|
||||
./live_migration.py --source-dump /pfad/pfosten_2026-10-29_180000.sql
|
||||
|
||||
Achtung: Schritt 3 leert die Live-DB. Das Script fragt vorher explizit nach
|
||||
und legt vorher ein Backup der vorhandenen Live-Tabellen an.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
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")
|
||||
COMPOSE_FILE = os.path.join(TOOLS_DIR, "docker-compose.yml")
|
||||
IMPORT_SCRIPT = os.path.join(TOOLS_DIR, "import_from_dump.sh")
|
||||
|
||||
DEFAULT_DUMP_DIR = "/home/torsten/repos/tippspiel/tools"
|
||||
DEFAULT_BACKUP_DIR = os.path.expanduser("~/backups/tippspiel-live")
|
||||
REMOTE_ROOT = "tippspiel"
|
||||
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",
|
||||
}
|
||||
|
||||
# Legacy-Live-DB als Quelle (siehe tools/sync_live_to_test.sh)
|
||||
LEGACY_DB = {
|
||||
"host": os.environ.get("LEGACY_HOST", "hoschis-tippspiel.de"),
|
||||
"port": os.environ.get("LEGACY_PORT", "3306"),
|
||||
"user": os.environ.get("LEGACY_USER", "d0274241"),
|
||||
"password": os.environ.get("LEGACY_PASS", "superpfosten!"),
|
||||
"name": os.environ.get("LEGACY_DB", "d0274241"),
|
||||
}
|
||||
|
||||
# Env-Variablen, die bei Bedarf aus den Credentials in die .htaccess wandern
|
||||
OPTIONAL_ENV_PREFIXES = ("APIFOOTBALL_", "SMTP_", "MAIL_")
|
||||
|
||||
# Reihenfolge der Env-Variablen in der .htaccess
|
||||
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 MigrationError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def log(message=""):
|
||||
print(message, flush=True)
|
||||
|
||||
|
||||
def timestamp():
|
||||
return datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
||||
|
||||
|
||||
def restrict_permissions(path):
|
||||
"""Setzt restriktive Rechte (0600) auf Dateien mit personenbezogenen Daten."""
|
||||
try:
|
||||
os.chmod(path, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_private_dir(path):
|
||||
"""Legt ein Verzeichnis an und beschränkt es auf den eigenen User (0700)."""
|
||||
os.makedirs(path, mode=0o700, exist_ok=True)
|
||||
try:
|
||||
os.chmod(path, 0o700)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Prozess-Helfer
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def run(cmd, env=None, stdin_path=None, capture=True, check=True):
|
||||
"""Führt einen Befehl aus und liefert stdout (bytes) bzw. None."""
|
||||
stdin = open(stdin_path, "rb") if stdin_path else subprocess.DEVNULL
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
env=env,
|
||||
stdin=stdin,
|
||||
stdout=subprocess.PIPE if capture else None,
|
||||
stderr=subprocess.PIPE if capture else None,
|
||||
)
|
||||
finally:
|
||||
if stdin_path:
|
||||
stdin.close()
|
||||
|
||||
if check and proc.returncode != 0:
|
||||
stderr = ""
|
||||
if capture and proc.stderr:
|
||||
stderr = proc.stderr.decode("utf-8", "replace").strip()
|
||||
raise MigrationError(
|
||||
"Befehl fehlgeschlagen (Exit %d): %s\n%s"
|
||||
% (proc.returncode, " ".join(cmd), stderr)
|
||||
)
|
||||
return proc.stdout if capture else None
|
||||
|
||||
|
||||
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, db=True):
|
||||
return run(
|
||||
mysql_cmd(conn, db=db) + ["-N", "-B", "-e", sql],
|
||||
env=mysql_env(conn),
|
||||
).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def mysqldump_cmd(conn):
|
||||
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"]),
|
||||
str(conn["name"]),
|
||||
]
|
||||
|
||||
|
||||
def dump_database(conn, path):
|
||||
"""Schreibt einen konsistenten SQL-Dump nach path."""
|
||||
with open(path, "wb") as out:
|
||||
proc = subprocess.run(
|
||||
mysqldump_cmd(conn),
|
||||
env=mysql_env(conn),
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=out,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise MigrationError(
|
||||
"mysqldump für '%s' fehlgeschlagen:\n%s"
|
||||
% (conn["name"], proc.stderr.decode("utf-8", "replace").strip())
|
||||
)
|
||||
if os.path.getsize(path) == 0:
|
||||
raise MigrationError("Dump von '%s' ist leer: %s" % (conn["name"], path))
|
||||
# Dumps enthalten E-Mails, PayPal-Adressen und IBAN-Ciphertexte
|
||||
restrict_permissions(path)
|
||||
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
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Credentials / Konfiguration
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
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 compose_iban_key():
|
||||
"""Liest den lokalen IBAN_KEY (muss zum Live-Key passen).
|
||||
|
||||
Reihenfolge: Umgebungsvariable IBAN_KEY, tools/.env (gitignored),
|
||||
tools/docker-compose.yml (Altbestand).
|
||||
"""
|
||||
env_key = os.environ.get("IBAN_KEY")
|
||||
if env_key:
|
||||
return env_key
|
||||
|
||||
env_file = os.path.join(TOOLS_DIR, ".env")
|
||||
try:
|
||||
with open(env_file, "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
|
||||
|
||||
try:
|
||||
with open(COMPOSE_FILE, "r", encoding="utf-8") as handle:
|
||||
text = handle.read()
|
||||
except OSError:
|
||||
return None
|
||||
match = re.search(r"^\s*-\s*IBAN_KEY=(.*)$", text, re.MULTILINE)
|
||||
return match.group(1).strip() if match else None
|
||||
|
||||
|
||||
def optional_env(creds, args):
|
||||
values = {}
|
||||
for key, value in creds.items():
|
||||
upper = key.upper()
|
||||
if upper.startswith(OPTIONAL_ENV_PREFIXES) and value:
|
||||
values[upper] = value
|
||||
if args.apifootball_key:
|
||||
values["APIFOOTBALL_KEY"] = args.apifootball_key
|
||||
return {k: v for k, v in values.items() if v}
|
||||
|
||||
|
||||
def htaccess_value(value):
|
||||
"""SetEnv-Werte müssen gequotet werden: Werte mit Leerzeichen (z. B.
|
||||
MAIL_FROM_NAME) führen sonst zu einem 500 auf jede Anfrage, weil Apache
|
||||
die Zeile nicht parsen kann."""
|
||||
escaped = str(value).replace("\\", "\\\\").replace('"', '\\"')
|
||||
return '"%s"' % escaped
|
||||
|
||||
|
||||
def build_htaccess(creds, args, db_host):
|
||||
values = {
|
||||
"DB_HOST": db_host,
|
||||
"DB_USER": creds.get("mysql_user") or creds["mysql_db"],
|
||||
"DB_PASS": creds["mysql_pw"],
|
||||
"DB_NEW_NAME": creds["mysql_db"],
|
||||
"APP_URL": args.app_url,
|
||||
"IBAN_KEY": creds.get("iban_key", ""),
|
||||
}
|
||||
values.update(optional_env(creds, args))
|
||||
|
||||
lines = [
|
||||
"# Auto-generiert von live_migration.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 newest_dump(dump_dir):
|
||||
candidates = sorted(
|
||||
os.path.join(dump_dir, name)
|
||||
for name in os.listdir(dump_dir)
|
||||
if name.startswith("pfosten") and name.endswith(".sql")
|
||||
) if os.path.isdir(dump_dir) else []
|
||||
candidates = [path for path in candidates if os.path.getsize(path) > 0]
|
||||
return candidates[-1] if candidates else None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Schritte
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def step_dump_legacy(args):
|
||||
dump_path = os.path.join(args.dump_dir, "pfosten_%s.sql" % timestamp())
|
||||
os.makedirs(args.dump_dir, exist_ok=True)
|
||||
log("== Schritt 1/4: Dump der Legacy-Live-DB ==")
|
||||
log(" Quelle: %s@%s/%s" % (LEGACY_DB["user"], LEGACY_DB["host"], LEGACY_DB["name"]))
|
||||
log(" Ziel: %s" % dump_path)
|
||||
dump_database(LEGACY_DB, dump_path)
|
||||
log(" OK, %.1f MB" % (os.path.getsize(dump_path) / 1024 / 1024))
|
||||
return dump_path
|
||||
|
||||
|
||||
def step_local_import(dump_path):
|
||||
log("")
|
||||
log("== Schritt 2/4: Lokaler Import + Migration ==")
|
||||
log(" Dump: %s" % dump_path)
|
||||
log(" Legacy-DB (Docker): %s" % "tippspiel_legacy")
|
||||
log(" Ziel-DB (Docker): %s" % LOCAL_DB["name"])
|
||||
env = dict(os.environ, DUMP=dump_path, DUMP_DIR=os.path.dirname(dump_path))
|
||||
run(["bash", IMPORT_SCRIPT], env=env, capture=False)
|
||||
|
||||
tables = list_tables(LOCAL_DB)
|
||||
if not tables:
|
||||
raise MigrationError("Lokale DB '%s' hat nach dem Import keine Tabellen." % LOCAL_DB["name"])
|
||||
counts = table_counts(LOCAL_DB, tables)
|
||||
if not counts.get("users"):
|
||||
raise MigrationError("Lokale DB '%s' enthält keine Users - Import fehlgeschlagen?" % LOCAL_DB["name"])
|
||||
log(" OK, %d Tabellen, %d Users, %d Tipps"
|
||||
% (len(tables), counts.get("users", 0), counts.get("tipps", 0)))
|
||||
|
||||
|
||||
def step_sync_live_db(args, live):
|
||||
log("")
|
||||
log("== Schritt 3/4: Live-DB '%s' auf %s aktualisieren ==" % (live["name"], live["host"]))
|
||||
|
||||
existing = list_tables(live)
|
||||
log(" Vorhandene Tabellen live: %d" % len(existing))
|
||||
|
||||
if existing:
|
||||
ensure_private_dir(args.backup_dir)
|
||||
backup_path = os.path.join(
|
||||
args.backup_dir, "live_%s_%s.sql" % (live["name"], timestamp())
|
||||
)
|
||||
log(" Sichere vorhandene Live-DB nach %s ..." % backup_path)
|
||||
dump_database(live, backup_path)
|
||||
log(" Backup OK, %.1f MB" % (os.path.getsize(backup_path) / 1024 / 1024))
|
||||
|
||||
local_tables = list_tables(LOCAL_DB)
|
||||
local_counts = table_counts(LOCAL_DB, local_tables)
|
||||
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 Tabellen live ..." % 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"]))
|
||||
run(mysql_cmd(live), env=mysql_env(live), stdin_path=dump_path)
|
||||
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 MigrationError("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 MigrationError("Zeilenanzahl weicht ab: %s" % ", ".join(mismatches))
|
||||
|
||||
log(" OK, %d Tabellen übernommen und verifiziert:" % len(remote_tables))
|
||||
for table in local_tables:
|
||||
if remote_counts.get(table):
|
||||
log(" %-16s %6d Zeilen" % (table, remote_counts[table]))
|
||||
|
||||
|
||||
def smoke_test(base_url):
|
||||
"""Prüft nach dem Deploy, ob die neue App wirklich ausgeliefert wird."""
|
||||
base = base_url.rstrip("/")
|
||||
log("")
|
||||
log("== Smoke-Test gegen %s ==" % base)
|
||||
failures = []
|
||||
|
||||
def fetch(path):
|
||||
request = urllib.request.Request(
|
||||
base + path, headers={"User-Agent": "live_migration/1.0"}
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
return (
|
||||
response.status,
|
||||
response.geturl(),
|
||||
response.headers.get_all("Set-Cookie") or [],
|
||||
response.read(300000),
|
||||
)
|
||||
|
||||
try:
|
||||
status, final_url, cookies, body = fetch("/")
|
||||
text = body.decode("utf-8", "replace")
|
||||
legacy = any("laravel_session" in cookie for cookie in cookies)
|
||||
if status != 200:
|
||||
failures.append("App: HTTP %d" % status)
|
||||
elif legacy:
|
||||
failures.append(
|
||||
"App: noch die Legacy-App erreichbar (laravel_session) - "
|
||||
"ist der Docroot schon auf /%s/public umgestellt?" % REMOTE_ROOT
|
||||
)
|
||||
elif "Datenbankverbindung fehlgeschlagen" in text:
|
||||
failures.append("App: DB-Verbindung fehlgeschlagen")
|
||||
elif "page=login" not in text:
|
||||
failures.append("App: Login-Seite der neuen App nicht erkannt")
|
||||
else:
|
||||
log(" [ok] App/Login erreichbar (%s)" % final_url)
|
||||
except urllib.error.HTTPError as exc:
|
||||
failures.append("App: HTTP %s" % exc.code)
|
||||
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 mkd_ignore_exists(ftp, name):
|
||||
try:
|
||||
ftp.mkd(name)
|
||||
except error_perm as exc:
|
||||
if not str(exc.args[0]).startswith("550"):
|
||||
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)
|
||||
if os.path.isfile(local_path):
|
||||
with open(local_path, "rb") as handle:
|
||||
ftp.storbinary("STOR " + name, handle)
|
||||
count += 1
|
||||
elif os.path.isdir(local_path):
|
||||
mkd_ignore_exists(ftp, name)
|
||||
ftp.cwd(name)
|
||||
count += upload_dir(ftp, local_path, remote_dir + "/" + name)
|
||||
ftp.cwd("..")
|
||||
return count
|
||||
|
||||
|
||||
def step_upload(args, creds, htaccess):
|
||||
log("")
|
||||
log("== Schritt 4/4: FTP-Upload nach /%s ==" % REMOTE_ROOT)
|
||||
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)
|
||||
ftp.cwd(REMOTE_ROOT)
|
||||
for sub in ("public", "src"):
|
||||
local_sub = os.path.join(APP_DIR, sub)
|
||||
if not os.path.isdir(local_sub):
|
||||
raise MigrationError("Lokales Verzeichnis fehlt: %s" % local_sub)
|
||||
log(" Lade %s/ hoch ..." % sub)
|
||||
mkd_ignore_exists(ftp, sub)
|
||||
ftp.cwd(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)
|
||||
ftp.cwd("..")
|
||||
|
||||
log(" Schreibe public/.htaccess ...")
|
||||
ftp.cwd("public")
|
||||
ftp.storbinary("STOR .htaccess", io.BytesIO(htaccess.encode("utf-8")))
|
||||
ftp.cwd("..")
|
||||
ftp.quit()
|
||||
except Exception:
|
||||
try:
|
||||
ftp.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Dry-Run
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def dry_run(args, creds, live):
|
||||
log("== Dry-Run: es wird nichts geschrieben ==")
|
||||
log("")
|
||||
log("Live-FTP: %s@%s, Zielordner /%s" % (creds["ftp_user"], creds["ftp_url"], REMOTE_ROOT))
|
||||
log("Live-DB: %s@%s/%s" % (live["user"], live["host"], live["name"]))
|
||||
log("App-URL: %s" % args.app_url)
|
||||
log("Dump-Dir: %s" % args.dump_dir)
|
||||
log("Backup-Dir:%s" % args.backup_dir)
|
||||
log("")
|
||||
|
||||
if args.source_dump:
|
||||
if os.path.isfile(args.source_dump):
|
||||
log("[ok] Source-Dump vorhanden: %s (%.1f MB)"
|
||||
% (args.source_dump, os.path.getsize(args.source_dump) / 1024 / 1024))
|
||||
else:
|
||||
log("[FEHLT] Source-Dump nicht gefunden: %s" % args.source_dump)
|
||||
elif args.skip_dump:
|
||||
found = newest_dump(args.dump_dir)
|
||||
if found:
|
||||
log("[ok] Neuester vorhandener Dump: %s" % found)
|
||||
else:
|
||||
log("[FEHLT] Kein pfosten*.sql in %s" % args.dump_dir)
|
||||
else:
|
||||
log("[plan] Würde Legacy-DB %s@%s/%s nach %s dumpen"
|
||||
% (LEGACY_DB["user"], LEGACY_DB["host"], LEGACY_DB["name"], args.dump_dir))
|
||||
|
||||
try:
|
||||
mysql_query(LOCAL_DB, "SELECT 1;")
|
||||
log("[ok] Lokale Docker-DB erreichbar (%s@%s:%s)"
|
||||
% (LOCAL_DB["user"], LOCAL_DB["host"], LOCAL_DB["port"]))
|
||||
except Exception as exc:
|
||||
log("[warn] Lokale Docker-DB nicht erreichbar: %s" % exc)
|
||||
|
||||
try:
|
||||
tables = list_tables(live)
|
||||
log("[ok] Live-DB-Login erfolgreich, %d vorhandene Tabellen%s"
|
||||
% (len(tables), " (werden gedroppt)" if tables else " (leer)"))
|
||||
except Exception as exc:
|
||||
log("[FEHLER] Live-DB-Login fehlgeschlagen: %s" % exc)
|
||||
|
||||
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 (".", "..")]
|
||||
has_root = REMOTE_ROOT in entries
|
||||
log("[ok] FTP-Login erfolgreich, Root: %s" % ", ".join(sorted(entries)))
|
||||
log(" Zielordner /%s %s" % (REMOTE_ROOT, "existiert bereits" if has_root else "wird neu angelegt"))
|
||||
ftp.quit()
|
||||
except Exception as exc:
|
||||
log("[FEHLER] FTP-Login fehlgeschlagen: %s" % exc)
|
||||
|
||||
log("")
|
||||
log("Geplante Schritte:")
|
||||
if args.skip_db_import:
|
||||
log(" - DB: übersprungen (--skip-db-import)")
|
||||
else:
|
||||
log(" - Legacy-Dump ziehen, lokal migrieren, Live-DB neu befüllen")
|
||||
if args.db_only:
|
||||
log(" - FTP: übersprungen (--db-only)")
|
||||
else:
|
||||
log(" - FTP: public/ + src/ nach /%s, .htaccess schreiben" % REMOTE_ROOT)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Main
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Go-Live: Legacy-Dump laden, lokal migrieren und ins "
|
||||
"Livesystem ausrollen (Live-DB + FTP-Ordner '%s')." % REMOTE_ROOT,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="Beispiele:\n"
|
||||
" %(prog)s --dry-run\n"
|
||||
" %(prog)s\n"
|
||||
" %(prog)s --db-only\n"
|
||||
" %(prog)s --skip-db-import\n",
|
||||
)
|
||||
parser.add_argument("--dry-run", action="store_true",
|
||||
help="nur prüfen (Zugänge, Dumps, Ziele), nichts ändern")
|
||||
parser.add_argument("--yes", action="store_true",
|
||||
help="ohne interaktive Rückfrage ausführen")
|
||||
parser.add_argument("--db-only", action="store_true",
|
||||
help="nur DB synchronisieren, keine Dateien hochladen")
|
||||
parser.add_argument("--skip-db-import", action="store_true",
|
||||
help="DB-Schritte überspringen (nur Dateien hochladen)")
|
||||
parser.add_argument("--skip-dump", action="store_true",
|
||||
help="keinen neuen Dump ziehen, neuesten vorhandenen nutzen")
|
||||
parser.add_argument("--source-dump", metavar="PFAD",
|
||||
help="vorhandenen Dump verwenden statt neu zu dumpen")
|
||||
parser.add_argument("--dump-dir", default=os.environ.get("DUMP_DIR", DEFAULT_DUMP_DIR),
|
||||
help="Verzeichnis für pfosten*.sql (Default: %(default)s)")
|
||||
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("--apifootball-key", default=os.environ.get("APIFOOTBALL_KEY"),
|
||||
help="optionaler APIFOOTBALL_KEY für die .htaccess")
|
||||
parser.add_argument("--skip-img-upload", action="store_true",
|
||||
help="public/img/ nicht hochladen")
|
||||
parser.add_argument("--check-url", nargs="?", const="", metavar="URL",
|
||||
help="nach dem Deploy einen HTTP-Smoke-Test ausführen "
|
||||
"(ohne Wert: APP_URL)")
|
||||
parser.add_argument("--check-only", action="store_true",
|
||||
help="nur den HTTP-Smoke-Test ausführen, nichts deployen")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
|
||||
if args.check_only:
|
||||
return 0 if smoke_test(args.check_url or args.app_url) else 1
|
||||
|
||||
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ürden IBANs im "
|
||||
"Klartext in die Live-DB geschrieben." % CRED_FILE)
|
||||
return 1
|
||||
local_key = compose_iban_key()
|
||||
if local_key and local_key != creds["iban_key"]:
|
||||
log("Fehler: lokaler IBAN_KEY (tools/.env bzw. tools/docker-compose.yml) weicht "
|
||||
"von 'iban_key' in %s ab." % CRED_FILE)
|
||||
log(" Lokal verschlüsselte IBANs wären live nicht lesbar.")
|
||||
return 1
|
||||
|
||||
live = live_connection(creds)
|
||||
app_db_host = creds.get("db_host") or "localhost"
|
||||
htaccess, written_env = build_htaccess(creds, args, app_db_host)
|
||||
|
||||
if args.dry_run:
|
||||
dry_run(args, creds, live)
|
||||
return 0
|
||||
|
||||
if args.skip_db_import and args.db_only:
|
||||
log("Fehler: --skip-db-import und --db-only zusammen ergeben nichts zu tun.")
|
||||
return 1
|
||||
|
||||
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
|
||||
"nur Dateien" if args.skip_db_import else
|
||||
"DB + Dateien"
|
||||
))
|
||||
log("")
|
||||
if "APIFOOTBALL_KEY" not in written_env:
|
||||
log("Hinweis: Kein APIFOOTBALL_KEY gesetzt - automatischer Ergebnisabruf "
|
||||
"bleibt live deaktiviert.")
|
||||
if "SMTP_HOST" not in written_env:
|
||||
log("Hinweis: Kein SMTP_HOST gesetzt - Mailversand (Rundmails/Erinnerungen) "
|
||||
"bleibt live deaktiviert.")
|
||||
log("")
|
||||
log("ACHTUNG: Die Live-DB wird geleert und neu befüllt.")
|
||||
if not args.yes:
|
||||
answer = input("Zum Fortfahren 'JA' eingeben: ").strip()
|
||||
if answer != "JA":
|
||||
log("Abgebrochen.")
|
||||
return 1
|
||||
|
||||
try:
|
||||
if not args.skip_db_import:
|
||||
if args.source_dump:
|
||||
dump_path = args.source_dump
|
||||
if not os.path.isfile(dump_path):
|
||||
raise MigrationError("Source-Dump nicht gefunden: %s" % dump_path)
|
||||
log("== Schritt 1/4: Dump der Legacy-Live-DB ==")
|
||||
log(" Verwende vorhandenen Dump: %s" % dump_path)
|
||||
elif args.skip_dump:
|
||||
dump_path = newest_dump(args.dump_dir)
|
||||
if not dump_path:
|
||||
raise MigrationError("Kein pfosten*.sql in %s gefunden." % args.dump_dir)
|
||||
log("== Schritt 1/4: Dump der Legacy-Live-DB ==")
|
||||
log(" Verwende neuesten vorhandenen Dump: %s" % dump_path)
|
||||
else:
|
||||
dump_path = step_dump_legacy(args)
|
||||
|
||||
step_local_import(dump_path)
|
||||
step_sync_live_db(args, live)
|
||||
|
||||
if not args.db_only:
|
||||
step_upload(args, creds, htaccess)
|
||||
|
||||
if args.check_url is not None:
|
||||
if args.db_only:
|
||||
log("Hinweis: --check-url wird bei --db-only übersprungen.")
|
||||
elif not smoke_test(args.check_url or args.app_url):
|
||||
log("")
|
||||
log("WARNUNG: Smoke-Test fehlgeschlagen. Die Dateien sind "
|
||||
"hochgeladen, die App liefert aber (noch) nicht wie erwartet "
|
||||
"aus - z. B. weil der Docroot noch auf die Legacy-App zeigt.")
|
||||
return 1
|
||||
|
||||
except MigrationError as exc:
|
||||
log("")
|
||||
log("FEHLER: %s" % exc)
|
||||
return 1
|
||||
|
||||
log("")
|
||||
log("Fertig.")
|
||||
log(" App: https://%s (FTP-Ordner /%s)" % (creds["ftp_url"], REMOTE_ROOT))
|
||||
if not args.db_only:
|
||||
log(" .htaccess liegt in /%s/public/.htaccess" % REMOTE_ROOT)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Synchronisiert alle 5 Minuten nur die Tipps der Legacy-Live-DB in das Testsystem.
|
||||
#
|
||||
# Ablauf pro Zyklus:
|
||||
# 1. Dump der Tabelle `tipps` aus der Legacy-Live-DB (nur Daten, kein Schema)
|
||||
# 2. Remote-Test-DB-Tabelle `tipps` leeren
|
||||
# 3. Dump in die Remote-Test-DB einspielen (Schema bleibt unverändert)
|
||||
#
|
||||
# Aufruf:
|
||||
# ./sync_live_to_test.sh Endlosschleife (alle 5 Minuten)
|
||||
# ./sync_live_to_test.sh --once genau ein Durchlauf
|
||||
#
|
||||
# Intervall über SYNC_INTERVAL (Sekunden) überschreibbar, z.B.:
|
||||
# SYNC_INTERVAL=60 ./sync_live_to_test.sh
|
||||
|
||||
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
|
||||
CRED_FILE="$REPO_ROOT/docs/testsystem_credentials.txt"
|
||||
|
||||
# Legacy-Live-DB (Quelle)
|
||||
LEGACY_HOST="${LEGACY_HOST:-hoschis-tippspiel.de}"
|
||||
LEGACY_USER="${LEGACY_USER:-d0274241}"
|
||||
LEGACY_PASS="${LEGACY_PASS:-superpfosten!}"
|
||||
LEGACY_DB="${LEGACY_DB:-d0274241}"
|
||||
|
||||
# Remote-Test-DB (Ziel) - DB-Name und Passwort kommen aus den Credentials
|
||||
REMOTE_HOST="${REMOTE_HOST:-programmschmiede.de}"
|
||||
REMOTE_PORT="${REMOTE_PORT:-3306}"
|
||||
REMOTE_USER="${REMOTE_USER:-d0489c69}"
|
||||
|
||||
INTERVAL="${SYNC_INTERVAL:-300}"
|
||||
|
||||
read_cred() {
|
||||
local key="$1"
|
||||
local val
|
||||
val="$(grep -E "^[[:space:]]*${key}[[:space:]]*=" "$CRED_FILE" | tail -1 | sed -E 's/^[^=]*=[[:space:]]*//' | tr -d '\r')"
|
||||
if [[ -z "$val" ]]; then
|
||||
echo "Fehler: Eintrag '$key' fehlt in $CRED_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s' "$val"
|
||||
}
|
||||
|
||||
run_once() {
|
||||
local remote_db remote_pw dump_file
|
||||
remote_db="$(read_cred mysql_db)"
|
||||
remote_pw="$(read_cred mysql_pw)"
|
||||
dump_file="$(mktemp /tmp/tipps_sync_XXXXXX.sql)"
|
||||
trap 'rm -f "$dump_file"' RETURN
|
||||
|
||||
echo "[$(date '+%F %T')] Dump der Tabelle 'tipps' aus der Legacy-Live-DB..."
|
||||
MYSQL_PWD="$LEGACY_PASS" mysqldump \
|
||||
--no-tablespaces --column-statistics=0 \
|
||||
--no-create-info --complete-insert \
|
||||
--skip-add-locks --skip-comments --skip-triggers \
|
||||
-h "$LEGACY_HOST" -u "$LEGACY_USER" "$LEGACY_DB" tipps > "$dump_file"
|
||||
|
||||
if ! grep -q "INSERT INTO" "$dump_file"; then
|
||||
echo "Fehler: Dump enthält keine Tipps (kein INSERT INTO)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[$(date '+%F %T')] Leere 'tipps' in der Remote-Test-DB..."
|
||||
MYSQL_PWD="$remote_pw" mysql \
|
||||
-h "$REMOTE_HOST" -P "$REMOTE_PORT" -u "$REMOTE_USER" "$remote_db" \
|
||||
-e "TRUNCATE TABLE \`tipps\`;"
|
||||
|
||||
echo "[$(date '+%F %T')] Spiele Tipps in die Remote-Test-DB ein..."
|
||||
MYSQL_PWD="$remote_pw" mysql \
|
||||
-h "$REMOTE_HOST" -P "$REMOTE_PORT" -u "$REMOTE_USER" "$remote_db" < "$dump_file"
|
||||
|
||||
echo "[$(date '+%F %T')] Zyklus abgeschlossen."
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == "--once" ]]; then
|
||||
run_once
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Starte Sync-Schleife (alle ${INTERVAL}s). Beenden mit Strg+C."
|
||||
while true; do
|
||||
run_once || true
|
||||
echo "Warte ${INTERVAL}s..."
|
||||
sleep "$INTERVAL"
|
||||
done
|
||||
Loading…
Add table
Add a link
Reference in a new issue