update
This commit is contained in:
parent
9e6b96fb0d
commit
667ae29560
19 changed files with 1854 additions and 70 deletions
790
tools/live_migration.py
Executable file
790
tools/live_migration.py
Executable file
|
|
@ -0,0 +1,790 @@
|
|||
#!/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())
|
||||
Loading…
Add table
Add a link
Reference in a new issue