update
This commit is contained in:
parent
9e6b96fb0d
commit
667ae29560
19 changed files with 1854 additions and 70 deletions
|
|
@ -71,7 +71,6 @@ def build_htaccess(creds):
|
|||
"SetEnv DB_NEW_NAME " + creds["mysql_db"],
|
||||
"SetEnv APP_URL " + APP_URL,
|
||||
"SetEnv IBAN_KEY " + creds.get("iban_key", ""),
|
||||
"SetEnv REMINDER_TOKEN " + creds.get("reminder_token", ""),
|
||||
"SetEnv APIFOOTBALL_KEY " + creds.get("apifootball_key", ""),
|
||||
"",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -20,11 +20,10 @@ services:
|
|||
- MAIL_FROM=hoschis.tippspiel.info@gmail.com
|
||||
- MAIL_FROM_NAME=Hoschis Tippspiel
|
||||
- APP_URL=http://localhost:8080
|
||||
- REMINDER_TOKEN=lokal-geheim
|
||||
# Schlüssel für die IBAN-Verschlüsselung (base64, 32 Byte).
|
||||
# MUSS mit "iban_key" in docs/testsystem_credentials.txt übereinstimmen:
|
||||
# die lokale DB wird verschlüsselt und per deploy_test.py zur Remote synct.
|
||||
- IBAN_KEY=/eG0tnvUGe02AR3ABgIJyMQdujnilxK7NkXhQubd3Rw=
|
||||
# Wird aus tools/.env gelesen (gitignored). MUSS zum "iban_key" in
|
||||
# docs/live_credentials.txt passen.
|
||||
- IBAN_KEY=${IBAN_KEY:-}
|
||||
# API Key für api-sports.io
|
||||
- APIFOOTBALL_KEY=269586edd11d7fde903f692810326004
|
||||
depends_on:
|
||||
|
|
|
|||
220
tools/dump_tippspiel.py
Executable file
220
tools/dump_tippspiel.py
Executable file
|
|
@ -0,0 +1,220 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Dumpt die Live-DB des Tippspiels nach tools/dumps.
|
||||
|
||||
Aufruf:
|
||||
./dump_tippspiel.py # Dump nach tools/dumps, 14 Dumps behalten
|
||||
./dump_tippspiel.py --keep 30 # 30 Dumps behalten
|
||||
./dump_tippspiel.py --keep 0 # nichts aufräumen
|
||||
./dump_tippspiel.py --dir /pfad # anderes Zielverzeichnis
|
||||
./dump_tippspiel.py --check # nur Verbindung/Parameter prüfen
|
||||
|
||||
Zugangsdaten kommen aus docs/live_credentials.txt (gitignored), überschreibbar
|
||||
per Umgebungsvariablen DB_HOST / DB_PORT / DB_USER / DB_PASS / DB_NAME.
|
||||
|
||||
Die Dumps enthalten personenbezogene Daten (E-Mails, PayPal-Adressen,
|
||||
IBAN-Ciphertexte) und werden deshalb mit 0600 in einem 0700-Verzeichnis
|
||||
abgelegt. Alte Dumps werden nur nach dem Muster tippspiel_live_*.sql gelöscht.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CRED_FILE = os.path.join(REPO_ROOT, "docs", "live_credentials.txt")
|
||||
DEFAULT_DUMP_DIR = os.path.join(REPO_ROOT, "tools", "dumps")
|
||||
DUMP_PATTERN = "tippspiel_live_*.sql"
|
||||
DEFAULT_KEEP = 14
|
||||
|
||||
|
||||
def log(message=""):
|
||||
print(message, flush=True)
|
||||
|
||||
|
||||
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 connection():
|
||||
if not os.path.isfile(CRED_FILE):
|
||||
raise SystemExit("Fehler: Credentials nicht gefunden: %s" % CRED_FILE)
|
||||
|
||||
creds = read_credentials(CRED_FILE)
|
||||
missing = [key for key in ("ftp_url", "mysql_db", "mysql_pw") if not creds.get(key)]
|
||||
if missing:
|
||||
raise SystemExit(
|
||||
"Fehler: Fehlende Einträge in %s: %s" % (CRED_FILE, ", ".join(missing))
|
||||
)
|
||||
|
||||
return {
|
||||
"host": os.environ.get("DB_HOST") or creds.get("db_host") or creds["ftp_url"],
|
||||
"port": os.environ.get("DB_PORT") or creds.get("db_port") or "3306",
|
||||
"user": os.environ.get("DB_USER") or creds.get("mysql_user") or creds["mysql_db"],
|
||||
"password": os.environ.get("DB_PASS") or creds["mysql_pw"],
|
||||
"name": os.environ.get("DB_NAME") or creds["mysql_db"],
|
||||
}
|
||||
|
||||
|
||||
def dump_command(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 ensure_private_dir(path):
|
||||
os.makedirs(path, mode=0o700, exist_ok=True)
|
||||
try:
|
||||
os.chmod(path, 0o700)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def check_connection(conn):
|
||||
env = dict(os.environ, MYSQL_PWD=str(conn["password"]))
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"mysql",
|
||||
"--connect-timeout=15",
|
||||
"--default-character-set=utf8mb4",
|
||||
"-h", str(conn["host"]),
|
||||
"-P", str(conn["port"]),
|
||||
"-u", str(conn["user"]),
|
||||
"-N", "-B", "-e", "SELECT 1;",
|
||||
str(conn["name"]),
|
||||
],
|
||||
env=env,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit(
|
||||
"Fehler: Datenbank nicht erreichbar:\n%s"
|
||||
% proc.stderr.decode("utf-8", "replace").strip()
|
||||
)
|
||||
|
||||
|
||||
def dump_database(conn, path):
|
||||
env = dict(os.environ, MYSQL_PWD=str(conn["password"]))
|
||||
with open(path, "wb") as out:
|
||||
proc = subprocess.run(
|
||||
dump_command(conn),
|
||||
env=env,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=out,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit(
|
||||
"Fehler: mysqldump fehlgeschlagen:\n%s"
|
||||
% proc.stderr.decode("utf-8", "replace").strip()
|
||||
)
|
||||
if os.path.getsize(path) == 0:
|
||||
raise SystemExit("Fehler: Dump ist leer: %s" % path)
|
||||
os.chmod(path, 0o600)
|
||||
return path
|
||||
|
||||
|
||||
def prune(dump_dir, keep):
|
||||
if keep <= 0:
|
||||
return []
|
||||
dumps = sorted(glob.glob(os.path.join(dump_dir, DUMP_PATTERN)))
|
||||
removed = []
|
||||
for path in dumps[:-keep]:
|
||||
try:
|
||||
os.unlink(path)
|
||||
removed.append(path)
|
||||
except OSError as exc:
|
||||
log(" Warnung: konnte %s nicht löschen: %s" % (path, exc))
|
||||
return removed
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Dumpt die Live-DB nach tools/dumps und räumt alte Dumps auf.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="Beispiele:\n"
|
||||
" %(prog)s\n"
|
||||
" %(prog)s --keep 30\n"
|
||||
" %(prog)s --keep 0\n"
|
||||
" %(prog)s --check\n",
|
||||
)
|
||||
parser.add_argument("--dir", default=os.environ.get("DUMP_DIR", DEFAULT_DUMP_DIR),
|
||||
help="Zielverzeichnis (Default: %(default)s)")
|
||||
parser.add_argument("--keep", type=int, default=DEFAULT_KEEP,
|
||||
help="Anzahl aufzubewahrender Dumps, 0 = nichts löschen "
|
||||
"(Default: %(default)s)")
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="nur Verbindung und Parameter prüfen, keinen Dump schreiben")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.keep < 0:
|
||||
parser.error("--keep darf nicht negativ sein")
|
||||
|
||||
conn = connection()
|
||||
log("Ziel: %s@%s:%s/%s" % (conn["user"], conn["host"], conn["port"], conn["name"]))
|
||||
|
||||
try:
|
||||
check_connection(conn)
|
||||
except SystemExit:
|
||||
raise
|
||||
log("Login: OK")
|
||||
|
||||
if args.check:
|
||||
log("Check beendet, kein Dump geschrieben.")
|
||||
return 0
|
||||
|
||||
ensure_private_dir(args.dir)
|
||||
stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
||||
final_path = os.path.join(args.dir, "tippspiel_live_%s.sql" % stamp)
|
||||
|
||||
fd, tmp_path = tempfile.mkstemp(prefix=".tippspiel_dump_", suffix=".tmp", dir=args.dir)
|
||||
os.close(fd)
|
||||
try:
|
||||
dump_database(conn, tmp_path)
|
||||
os.replace(tmp_path, final_path)
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
|
||||
size_mb = os.path.getsize(final_path) / 1024 / 1024
|
||||
log("Dump: %s (%.1f MB, 0600)" % (final_path, size_mb))
|
||||
|
||||
removed = prune(args.dir, args.keep)
|
||||
for path in removed:
|
||||
log("Alte Datei gelöscht: %s" % path)
|
||||
remaining = sorted(glob.glob(os.path.join(args.dir, DUMP_PATTERN)))
|
||||
log("Vorhanden: %d Dump(s)%s" % (
|
||||
len(remaining),
|
||||
"" if args.keep <= 0 else " (keep=%d)" % args.keep,
|
||||
))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(130)
|
||||
291
tools/import_accounts.php
Normal file
291
tools/import_accounts.php
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
<?php
|
||||
|
||||
// Importiert IBAN und Mobilnummern aus einem Kontodaten-CSV
|
||||
// (erzeugt von export_accounts.php) in die users-Tabelle der Zieldatenbank.
|
||||
//
|
||||
// Aufruf (im App-Container):
|
||||
// docker compose exec app php import_accounts.php <pfad.csv> [--apply]
|
||||
//
|
||||
// Ohne --apply wird nur geprüft und berichtet, es wird nichts geschrieben.
|
||||
//
|
||||
// Verhalten:
|
||||
// - Zuordnung über user_id, zusätzlich wird die E-Mail-Adresse verglichen.
|
||||
// - Leere Felder werden gefüllt; bereits gesetzte Werte werden nicht
|
||||
// überschrieben (der neuere Stand in der App gewinnt).
|
||||
// - IBANs werden mit dem Schlüssel aus IBAN_KEY verschlüsselt (App\Core\Crypto).
|
||||
// - Ist IBAN_KEY_OLD gesetzt, werden vorhandene, noch mit dem alten Schlüssel
|
||||
// verschlüsselte IBANs auf den neuen Schlüssel umgeschlüsselt.
|
||||
//
|
||||
// Beispiel (Live, Schlüsselwechsel + Import):
|
||||
// docker compose exec -T \
|
||||
// -e DB_HOST=... -e DB_USER=... -e DB_PASS=... -e DB_NEW_NAME=... \
|
||||
// -e IBAN_KEY="<neu>" -e IBAN_KEY_OLD="<alt>" \
|
||||
// app php import_accounts.php export_kontodaten_20261023_130939.csv --apply
|
||||
|
||||
$apply = false;
|
||||
$csvPath = null;
|
||||
foreach (array_slice($argv, 1) as $arg) {
|
||||
if ($arg === '--apply') {
|
||||
$apply = true;
|
||||
} elseif ($arg === '--help' || $arg === '-h') {
|
||||
echo "Aufruf: php import_accounts.php <datei.csv> [--apply]\n";
|
||||
exit(0);
|
||||
} elseif ($csvPath === null) {
|
||||
$csvPath = $arg;
|
||||
} else {
|
||||
fwrite(STDERR, "Unbekanntes Argument: $arg\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if ($csvPath === null) {
|
||||
$candidates = glob(__DIR__ . '/export_kontodaten_*.csv') ?: [];
|
||||
sort($candidates);
|
||||
$csvPath = end($candidates) ?: null;
|
||||
}
|
||||
if ($csvPath === null || !is_file($csvPath)) {
|
||||
fwrite(STDERR, "Fehler: CSV-Datei nicht gefunden.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$host = getenv('DB_HOST') ?: '127.0.0.1';
|
||||
$port = (int)(getenv('DB_PORT') ?: 3306);
|
||||
$user = getenv('DB_USER') ?: 'root';
|
||||
$pass = getenv('DB_PASS') ?: '';
|
||||
$dbName = getenv('DB_NEW_NAME') ?: 'tippspiel2027';
|
||||
|
||||
// Crypto-Klasse laden (funktioniert im Container und direkt auf dem Host).
|
||||
$cryptoCandidates = [
|
||||
__DIR__ . '/../tippspiel/src/Core/Crypto.php',
|
||||
__DIR__ . '/src/Core/Crypto.php',
|
||||
];
|
||||
$cryptoFile = null;
|
||||
foreach ($cryptoCandidates as $candidate) {
|
||||
if (file_exists($candidate)) {
|
||||
$cryptoFile = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($cryptoFile === null) {
|
||||
die("Fehler: Crypto.php nicht gefunden.\n");
|
||||
}
|
||||
require_once $cryptoFile;
|
||||
|
||||
$ibanCandidates = [
|
||||
__DIR__ . '/../tippspiel/src/Core/Iban.php',
|
||||
__DIR__ . '/src/Core/Iban.php',
|
||||
];
|
||||
$ibanFile = null;
|
||||
foreach ($ibanCandidates as $candidate) {
|
||||
if (file_exists($candidate)) {
|
||||
$ibanFile = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($ibanFile === null) {
|
||||
die("Fehler: Iban.php nicht gefunden.\n");
|
||||
}
|
||||
require_once $ibanFile;
|
||||
|
||||
use App\Core\Crypto;
|
||||
use App\Core\Iban;
|
||||
|
||||
function maskedIban($iban) {
|
||||
$iban = (string)$iban;
|
||||
return strlen($iban) <= 6 ? '…' : substr($iban, 0, 4) . '…' . substr($iban, -4);
|
||||
}
|
||||
|
||||
try {
|
||||
$newKey = (string)getenv('IBAN_KEY');
|
||||
if (Crypto::key() === null) {
|
||||
die("Fehler: IBAN_KEY ist nicht gesetzt. Schlüssel erzeugen mit: openssl rand -base64 32\n");
|
||||
}
|
||||
$oldKey = (string)getenv('IBAN_KEY_OLD');
|
||||
|
||||
$pdo = new PDO("mysql:host=$host;port=$port;dbname=$dbName;charset=utf8mb4", $user, $pass);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
echo ($apply ? "MODUS: schreiben" : "MODUS: Vorschau (nichts wird geschrieben)")
|
||||
. "\nZiel: {$user}@{$host}:{$port}/{$dbName}\n\n";
|
||||
|
||||
// Bestand laden
|
||||
$users = [];
|
||||
foreach ($pdo->query("SELECT id, email, iban, mobile FROM users") as $row) {
|
||||
$users[(int)$row['id']] = $row;
|
||||
}
|
||||
|
||||
$updateIban = $pdo->prepare(
|
||||
"UPDATE users SET iban = ?, updated_at = NOW() WHERE id = ? AND (iban IS NULL OR iban = '')"
|
||||
);
|
||||
$updateMobile = $pdo->prepare(
|
||||
"UPDATE users SET mobile = ?, updated_at = NOW() WHERE id = ? AND (mobile IS NULL OR mobile = '')"
|
||||
);
|
||||
$updateExistingIban = $pdo->prepare("UPDATE users SET iban = ?, updated_at = NOW() WHERE id = ?");
|
||||
|
||||
// 1) Vorhandene IBANs auf den neuen Schlüssel umschlüsseln
|
||||
$rekeyed = 0;
|
||||
$rekeyFailed = [];
|
||||
foreach ($users as $id => $row) {
|
||||
$iban = trim((string)$row['iban']);
|
||||
if ($iban === '') {
|
||||
continue;
|
||||
}
|
||||
if (Crypto::isEncrypted($iban)) {
|
||||
try {
|
||||
Crypto::decrypt($iban);
|
||||
continue; // bereits mit dem neuen Schlüssel lesbar
|
||||
} catch (\Throwable $e) {
|
||||
// mit altem Schlüssel versuchen
|
||||
}
|
||||
if ($oldKey === '') {
|
||||
$rekeyFailed[] = $id;
|
||||
continue;
|
||||
}
|
||||
putenv('IBAN_KEY=' . $oldKey);
|
||||
try {
|
||||
$plain = Crypto::decrypt($iban);
|
||||
} catch (\Throwable $e) {
|
||||
putenv('IBAN_KEY=' . $newKey);
|
||||
$rekeyFailed[] = $id;
|
||||
continue;
|
||||
}
|
||||
putenv('IBAN_KEY=' . $newKey);
|
||||
$cipher = Crypto::encrypt($plain);
|
||||
if ($apply) {
|
||||
$updateExistingIban->execute([$cipher, $id]);
|
||||
}
|
||||
$users[$id]['iban'] = $cipher;
|
||||
$rekeyed++;
|
||||
} else {
|
||||
// Klartext aus Altbestand
|
||||
$cipher = Crypto::encrypt($iban);
|
||||
if ($apply) {
|
||||
$updateExistingIban->execute([$cipher, $id]);
|
||||
}
|
||||
$users[$id]['iban'] = $cipher;
|
||||
$rekeyed++;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) CSV einlesen
|
||||
$fh = fopen($csvPath, 'r');
|
||||
if ($fh === false) {
|
||||
die("Fehler: CSV kann nicht geöffnet werden: $csvPath\n");
|
||||
}
|
||||
$header = fgetcsv($fh, 0, ';');
|
||||
if ($header === false) {
|
||||
die("Fehler: CSV ist leer.\n");
|
||||
}
|
||||
$header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]);
|
||||
$columns = array_flip($header);
|
||||
foreach (['user_id', 'email', 'iban', 'mobile'] as $required) {
|
||||
if (!isset($columns[$required])) {
|
||||
die("Fehler: Spalte '$required' fehlt im CSV.\n");
|
||||
}
|
||||
}
|
||||
|
||||
$rows = 0;
|
||||
$missing = [];
|
||||
$mismatch = [];
|
||||
$invalid = [];
|
||||
$ibanSet = 0;
|
||||
$ibanExists = 0;
|
||||
$ibanDiffers = [];
|
||||
$mobileSet = 0;
|
||||
$mobileExists = 0;
|
||||
|
||||
while (($line = fgetcsv($fh, 0, ';')) !== false) {
|
||||
if ($line === [null] || count($line) < count($header)) {
|
||||
continue;
|
||||
}
|
||||
$rows++;
|
||||
$id = (int)$line[$columns['user_id']];
|
||||
$email = trim((string)$line[$columns['email']]);
|
||||
|
||||
if (!isset($users[$id])) {
|
||||
$missing[] = $id;
|
||||
continue;
|
||||
}
|
||||
if (strcasecmp(trim((string)$users[$id]['email']), $email) !== 0) {
|
||||
$mismatch[] = $id;
|
||||
continue;
|
||||
}
|
||||
|
||||
$rawIban = trim((string)$line[$columns['iban']]);
|
||||
if ($rawIban !== '') {
|
||||
$iban = Iban::normalize($rawIban);
|
||||
if (!Iban::isValid($iban)) {
|
||||
$invalid[] = $id . ' (' . maskedIban($iban) . ')';
|
||||
} elseif (trim((string)$users[$id]['iban']) === '') {
|
||||
$cipher = Crypto::encrypt($iban);
|
||||
if ($apply) {
|
||||
$updateIban->execute([$cipher, $id]);
|
||||
}
|
||||
$users[$id]['iban'] = $cipher;
|
||||
$ibanSet++;
|
||||
} else {
|
||||
$ibanExists++;
|
||||
$existing = '';
|
||||
try {
|
||||
$existing = Iban::normalize(Crypto::decrypt($users[$id]['iban']));
|
||||
} catch (\Throwable $e) {
|
||||
$existing = null;
|
||||
}
|
||||
if ($existing !== $iban) {
|
||||
$ibanDiffers[] = $id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$mobile = trim((string)$line[$columns['mobile']]);
|
||||
if ($mobile !== '') {
|
||||
if (trim((string)$users[$id]['mobile']) === '') {
|
||||
if ($apply) {
|
||||
$updateMobile->execute([$mobile, $id]);
|
||||
}
|
||||
$users[$id]['mobile'] = $mobile;
|
||||
$mobileSet++;
|
||||
} else {
|
||||
$mobileExists++;
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose($fh);
|
||||
|
||||
echo "CSV: {$rows} Zeilen aus " . basename($csvPath) . "\n";
|
||||
echo "IBANs umgeschlüsselt/verschlüsselt: {$rekeyed}\n";
|
||||
echo "IBANs neu gesetzt: {$ibanSet}\n";
|
||||
echo "IBANs bereits vorhanden (behalten): {$ibanExists}\n";
|
||||
echo "Mobilnummern neu gesetzt: {$mobileSet}\n";
|
||||
echo "Mobilnummern bereits vorhanden: {$mobileExists}\n";
|
||||
|
||||
if ($ibanDiffers) {
|
||||
echo "Hinweis: abweichende vorhandene IBAN (App-Stand gewinnt), User-IDs: "
|
||||
. implode(', ', $ibanDiffers) . "\n";
|
||||
}
|
||||
if ($invalid) {
|
||||
echo "Ungültige IBAN im CSV (übersprungen): " . implode(', ', $invalid) . "\n";
|
||||
}
|
||||
if ($missing) {
|
||||
echo "Unbekannte User-IDs: " . implode(', ', $missing) . "\n";
|
||||
}
|
||||
if ($mismatch) {
|
||||
echo "E-Mail passt nicht zur User-ID: " . implode(', ', $mismatch) . "\n";
|
||||
}
|
||||
if ($rekeyFailed) {
|
||||
echo "WARNUNG: IBAN nicht entschlüsselbar (weder neuer noch alter Schlüssel), User-IDs: "
|
||||
. implode(', ', $rekeyFailed) . "\n";
|
||||
}
|
||||
|
||||
if (!$apply) {
|
||||
echo "\nVorschau beendet. Zum Schreiben --apply ergänzen.\n";
|
||||
} else {
|
||||
echo "\nImport abgeschlossen.\n";
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
fwrite(STDERR, "Datenbankfehler: " . $e->getMessage() . "\n");
|
||||
exit(1);
|
||||
} catch (\Throwable $e) {
|
||||
fwrite(STDERR, "Fehler: " . $e->getMessage() . "\n");
|
||||
exit(1);
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ 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="$(ls -1 "$DUMP_DIR"/pfosten*.sql | tail -1)"
|
||||
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
|
||||
|
|
|
|||
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