diff --git a/.gitignore b/.gitignore index d06667c..e9bc7b3 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ storage/* *.log .DS_Store .~lock.* +tools/dumps/ diff --git a/README.md b/README.md index 4631132..b5340ac 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,40 @@ Für `--install` werden `DIC_ADMIN_FIRST`, `DIC_ADMIN_LAST` und `DIC_ADMIN_PASSWORD` aus der Umgebung gelesen oder interaktiv abgefragt. `install.php` wird nach erfolgreicher Installation vom Server entfernt. +## Datenbank-Dumps (Backups) + +Für den Regelbetrieb gibt es ein eigenständiges Dump-Script: + +```bash +./tools/dump_drink_it_cold.py # Dump nach tools/dumps, 14 Stück behalten +./tools/dump_drink_it_cold.py --keep 30 # mehr Historie +./tools/dump_drink_it_cold.py --keep 0 # nichts aufräumen +./tools/dump_drink_it_cold.py --check # nur Verbindung prüfen +./tools/dump_drink_it_cold.py --dir /pfad # anderes Zielverzeichnis +``` + +- Zugangsdaten: `docs/credentials.txt` (`DB_HOST`, `DB_NAME`, `DB_USER`, + `DB_PASSWORD`); überschreibbar per `DB_HOST`, `DB_PORT`, `DB_USER`, + `DB_PASS`, `DB_NAME`. +- Dateiname: `tools/dumps/drink-it-cold_live_.sql` +- Rechte: Verzeichnis `0700`, Datei `0600` (Dumps enthalten Namen, Adressen, + Telefonnummern und E-Mail-Adressen). +- Aufräumen: standardmäßig bleiben die letzten 14 Dumps; gelöscht werden nur + Dateien nach dem Muster `drink-it-cold_live_*.sql`. +- `tools/dumps/` ist gitignored. + +Cron-Beispiel (täglich 03:30): + +``` +30 3 * * * /Users/torsten/repos/drink-it-cold/tools/dump_drink_it_cold.py >> /var/log/drink-it-cold-dump.log 2>&1 +``` + +Zurückspielen (Vorsicht: der Dump enthält `DROP TABLE`/`CREATE TABLE`): + +```bash +mysql -h -u -p < tools/dumps/drink-it-cold_live_<...>.sql +``` + ## Erinnerungen: Push, E-Mail und Cron Die Erinnerungen sind immer in der App sichtbar. Zusätzlich gibt es zwei diff --git a/tools/dump_drink_it_cold.py b/tools/dump_drink_it_cold.py new file mode 100755 index 0000000..4d2feeb --- /dev/null +++ b/tools/dump_drink_it_cold.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +""" +Dumpt die Remote-DB von Drink it cold nach tools/dumps. + +Aufruf: + ./dump_drink_it_cold.py # Dump nach tools/dumps, 14 Dumps behalten + ./dump_drink_it_cold.py --keep 30 # 30 Dumps behalten + ./dump_drink_it_cold.py --keep 0 # nichts aufräumen + ./dump_drink_it_cold.py --dir /pfad # anderes Zielverzeichnis + ./dump_drink_it_cold.py --check # nur Verbindung/Parameter prüfen + +Zugangsdaten kommen aus docs/credentials.txt (gitignored), überschreibbar per +Umgebungsvariablen DB_HOST / DB_PORT / DB_USER / DB_PASS / DB_NAME. + +Die Dumps enthalten personenbezogene Daten (Namen, Adressen, Telefonnummern, +E-Mail-Adressen) und werden deshalb mit 0600 in einem 0700-Verzeichnis +abgelegt. Alte Dumps werden nur nach dem Muster drink-it-cold_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", "credentials.txt") +DEFAULT_DUMP_DIR = os.path.join(REPO_ROOT, "tools", "dumps") +DUMP_PATTERN = "drink-it-cold_live_*.sql" +DEFAULT_KEEP = 14 + + +def log(message=""): + print(message, flush=True) + + +def read_credentials(path): + """Liest KEY: value (credentials.txt) und KEY=value (ältere Dateien).""" + creds = {} + with open(path, "r", encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if not line or line.startswith("#"): + continue + if "=" in line and (":" not in line or line.index("=") < line.index(":")): + key, _, value = line.partition("=") + elif ":" in line: + key, _, value = line.partition(":") + else: + continue + 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 ("DB_HOST", "DB_NAME", "DB_USER", "DB_PASSWORD") 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["DB_HOST"], + "port": os.environ.get("DB_PORT") or creds.get("DB_PORT") or "3306", + "user": os.environ.get("DB_USER") or creds["DB_USER"], + "password": os.environ.get("DB_PASS") or creds["DB_PASSWORD"], + "name": os.environ.get("DB_NAME") or creds["DB_NAME"], + } + + +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) + with open(path, "rb") as handle: + handle.seek(max(0, os.path.getsize(path) - 200)) + if b"Dump completed" not in handle.read(): + raise SystemExit("Fehler: Dump wirkt unvollständig (Abschlusszeile fehlt): %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 Remote-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"])) + + check_connection(conn) + 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, "drink-it-cold_live_%s.sql" % stamp) + + fd, tmp_path = tempfile.mkstemp(prefix=".drink-it-cold_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)