339 lines
11 KiB
Python
Executable file
339 lines
11 KiB
Python
Executable file
#!/usr/bin/python3
|
||
# Stellt ein Backup wieder her:
|
||
# - Dateien per FTPS nach /motorradig
|
||
# - Datenbank direkt über den MySQL-Zugang aus ../motorradig/.credentials
|
||
#
|
||
# Der DB-Import läuft nicht über FTP. Er verbindet sich – wie
|
||
# dump_motorradig.py – direkt mit dem Live-MySQL-Server. Ein Hosting-Panel
|
||
# oder SSH ist dafür nicht nötig.
|
||
#
|
||
# Beispiele:
|
||
# # Nur Dateien
|
||
# python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel>
|
||
#
|
||
# # Dateien und Datenbank
|
||
# python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --with-db
|
||
#
|
||
# # Nur Datenbank
|
||
# python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --db-only
|
||
#
|
||
# # Datenbank vorher komplett droppen und neu anlegen
|
||
# python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --db-only --drop-db
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import ftplib
|
||
import glob
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
|
||
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||
REPO_ROOT = os.path.normpath(os.path.join(TOOLS_DIR, '..'))
|
||
APP_ROOT = os.path.join(REPO_ROOT, 'motorradig')
|
||
CRED_FILE = os.path.join(APP_ROOT, '.credentials')
|
||
REMOTE_BASE = '/motorradig'
|
||
|
||
# Diese Datei gehört nur auf den lokalen Rechner, nicht auf den Webserver.
|
||
SKIP_FILES = {'.credentials'}
|
||
|
||
|
||
def load_credentials(path: str) -> dict:
|
||
creds = {}
|
||
if not os.path.isfile(path):
|
||
print(f'Fehler: Credentials-Datei nicht gefunden: {path}', file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
with open(path, 'r', encoding='utf-8') as fh:
|
||
for line in fh:
|
||
line = line.strip()
|
||
if not line or line.startswith('#') or '=' not in line:
|
||
continue
|
||
key, value = line.split('=', 1)
|
||
creds[key.strip()] = value.strip()
|
||
|
||
return creds
|
||
|
||
|
||
def connect(creds: dict) -> ftplib.FTP_TLS:
|
||
ftp = ftplib.FTP_TLS()
|
||
ftp.connect(creds['FTP_URL'], 21, timeout=30)
|
||
ftp.login(creds['FTP_USER'], creds['FTP_PASSWORD'])
|
||
ftp.prot_p()
|
||
ftp.set_pasv(True)
|
||
ftp.encoding = 'latin-1'
|
||
ftp.voidcmd('TYPE I')
|
||
return ftp
|
||
|
||
|
||
def ensure_remote_dir(ftp: ftplib.FTP, path: str) -> None:
|
||
current = ''
|
||
for part in path.split('/'):
|
||
if not part:
|
||
continue
|
||
current += '/' + part
|
||
try:
|
||
ftp.cwd(current)
|
||
except ftplib.all_errors:
|
||
try:
|
||
ftp.mkd(current)
|
||
ftp.cwd(current)
|
||
except ftplib.all_errors:
|
||
pass
|
||
|
||
|
||
def sha256(path: str) -> str:
|
||
digest = hashlib.sha256()
|
||
with open(path, 'rb') as fh:
|
||
for chunk in iter(lambda: fh.read(1024 * 1024), b''):
|
||
digest.update(chunk)
|
||
return digest.hexdigest()
|
||
|
||
|
||
def collect_files(files_root: str) -> list:
|
||
files = []
|
||
for dirpath, dirnames, filenames in os.walk(files_root):
|
||
dirnames[:] = sorted(d for d in dirnames if not d.startswith('.'))
|
||
for filename in sorted(filenames):
|
||
if filename in SKIP_FILES:
|
||
continue
|
||
local = os.path.join(dirpath, filename)
|
||
rel = os.path.relpath(local, files_root).replace(os.sep, '/')
|
||
files.append((local, rel))
|
||
return files
|
||
|
||
|
||
def load_manifest(backup_dir: str) -> dict:
|
||
manifest_path = os.path.join(backup_dir, 'manifest.json')
|
||
if not os.path.isfile(manifest_path):
|
||
return {}
|
||
|
||
with open(manifest_path, 'r', encoding='utf-8') as fh:
|
||
return json.load(fh)
|
||
|
||
|
||
def find_db_dump(backup_dir: str, manifest: dict) -> str | None:
|
||
relative = manifest.get('database_dump')
|
||
if relative:
|
||
path = os.path.join(backup_dir, relative)
|
||
if os.path.isfile(path):
|
||
return path
|
||
|
||
candidates = sorted(glob.glob(os.path.join(backup_dir, 'db', '*.sql')))
|
||
return candidates[-1] if candidates else None
|
||
|
||
|
||
def db_config(creds: dict) -> dict:
|
||
"""Ermittelt die Live-DB aus .credentials (wie dump_motorradig.py)."""
|
||
host = creds.get('DB_HOST', creds.get('FTP_URL', ''))
|
||
port = creds.get('DB_PORT', '3306')
|
||
user = creds.get('DB_USERNAME', '')
|
||
password = creds.get('DB_PASSWORD', '')
|
||
database = creds.get('DB_NAME', creds.get('DB_DATABASE', user))
|
||
|
||
missing = []
|
||
if not host:
|
||
missing.append('DB_HOST (oder FTP_URL)')
|
||
if not user:
|
||
missing.append('DB_USERNAME')
|
||
if not password:
|
||
missing.append('DB_PASSWORD')
|
||
if not database:
|
||
missing.append('DB_NAME (oder DB_USERNAME)')
|
||
|
||
if missing:
|
||
raise RuntimeError('Fehlende DB-Credentials: ' + ', '.join(missing))
|
||
|
||
if not re.fullmatch(r'[A-Za-z0-9_]+', database):
|
||
raise RuntimeError('Ungültiger Datenbankname: ' + database)
|
||
|
||
return {
|
||
'host': host,
|
||
'port': port,
|
||
'user': user,
|
||
'password': password,
|
||
'database': database,
|
||
}
|
||
|
||
|
||
def mysql_command(db: dict) -> list:
|
||
return [
|
||
'mysql',
|
||
'--host=' + db['host'],
|
||
'--port=' + db['port'],
|
||
'--user=' + db['user'],
|
||
'--password=' + db['password'],
|
||
'--default-character-set=utf8mb4',
|
||
]
|
||
|
||
|
||
def import_database(dump_path: str, db: dict, drop_db: bool) -> None:
|
||
base = mysql_command(db)
|
||
|
||
if drop_db:
|
||
sql = (
|
||
f'DROP DATABASE IF EXISTS `{db["database"]}`; '
|
||
f'CREATE DATABASE `{db["database"]}` '
|
||
'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'
|
||
)
|
||
print(f'Droppe und erstelle Datenbank {db["database"]} …')
|
||
try:
|
||
result = subprocess.run(base + ['--execute=' + sql], stderr=subprocess.PIPE)
|
||
except FileNotFoundError:
|
||
raise RuntimeError('mysql-Client nicht gefunden (apt install mysql-client).')
|
||
if result.returncode != 0:
|
||
raise RuntimeError(result.stderr.decode('utf-8', 'replace').strip())
|
||
|
||
print(f'Importiere {dump_path} nach {db["host"]}/{db["database"]} …')
|
||
try:
|
||
with open(dump_path, 'rb') as fh:
|
||
result = subprocess.run(base + [db['database']], stdin=fh, stderr=subprocess.PIPE)
|
||
except FileNotFoundError:
|
||
raise RuntimeError('mysql-Client nicht gefunden (apt install mysql-client).')
|
||
|
||
if result.returncode != 0:
|
||
raise RuntimeError(result.stderr.decode('utf-8', 'replace').strip())
|
||
|
||
|
||
def restore_files(creds: dict, files: list) -> None:
|
||
ftp = connect(creds)
|
||
try:
|
||
for index, (local, rel) in enumerate(files, start=1):
|
||
remote = REMOTE_BASE + '/' + rel
|
||
remote_dir, remote_name = remote.rsplit('/', 1)
|
||
|
||
ensure_remote_dir(ftp, remote_dir)
|
||
ftp.cwd(remote_dir)
|
||
print(f'[{index}/{len(files)}] {rel}')
|
||
with open(local, 'rb') as fh:
|
||
ftp.storbinary('STOR ' + remote_name, fh)
|
||
|
||
ftp.quit()
|
||
finally:
|
||
try:
|
||
ftp.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(
|
||
description='Backup wiederherstellen: Dateien per FTPS und/oder Datenbank direkt per MySQL.',
|
||
)
|
||
parser.add_argument('backup_dir', help='Verzeichnis des Backups (enthält db/, files/ und manifest.json).')
|
||
parser.add_argument('--db-only', action='store_true',
|
||
help='Nur die Datenbank importieren, keine Dateien hochladen.')
|
||
parser.add_argument('--with-db', action='store_true',
|
||
help='Nach den Dateien auch die Datenbank importieren.')
|
||
parser.add_argument('--drop-db', action='store_true',
|
||
help='Datenbank vor dem Import droppen und neu anlegen (impliziert DB-Import).')
|
||
parser.add_argument('--dry-run', action='store_true', help='Nur anzeigen, was passieren würde.')
|
||
parser.add_argument('--yes', action='store_true', help='Ohne Rückfrage wiederherstellen.')
|
||
parser.add_argument('--skip-verify', action='store_true', help='SHA256-Prüfung vor der Wiederherstellung überspringen.')
|
||
args = parser.parse_args()
|
||
|
||
backup_dir = os.path.abspath(args.backup_dir)
|
||
if not os.path.isdir(backup_dir):
|
||
print(f'Fehler: Backup-Verzeichnis fehlt: {backup_dir}', file=sys.stderr)
|
||
return 1
|
||
|
||
manifest = load_manifest(backup_dir)
|
||
files_enabled = not args.db_only
|
||
db_enabled = args.with_db or args.db_only or args.drop_db
|
||
|
||
files = []
|
||
if files_enabled:
|
||
files_root = os.path.join(backup_dir, 'files')
|
||
if not os.path.isdir(files_root):
|
||
print(f'Fehler: {files_root} fehlt.', file=sys.stderr)
|
||
return 1
|
||
|
||
files = collect_files(files_root)
|
||
if not files:
|
||
print('Fehler: Keine Dateien im Backup gefunden.', file=sys.stderr)
|
||
return 1
|
||
|
||
dump_path = None
|
||
if db_enabled:
|
||
dump_path = find_db_dump(backup_dir, manifest)
|
||
if not dump_path:
|
||
print('Fehler: Kein DB-Dump im Backup gefunden (db/*.sql).', file=sys.stderr)
|
||
return 1
|
||
|
||
# Prüfsummen
|
||
if not args.skip_verify:
|
||
hashes = {item['path']: item['sha256'] for item in manifest.get('files', [])}
|
||
expected_db = manifest.get('database_dump_sha256')
|
||
|
||
print('Prüfe SHA256 …')
|
||
for local, rel in files:
|
||
expected = hashes.get(rel)
|
||
if expected and sha256(local) != expected:
|
||
print(f'Fehler: Prüfsumme stimmt nicht: {rel}', file=sys.stderr)
|
||
return 1
|
||
if dump_path and expected_db and sha256(dump_path) != expected_db:
|
||
print('Fehler: Prüfsumme des DB-Dumps stimmt nicht.', file=sys.stderr)
|
||
return 1
|
||
|
||
total_bytes = sum(os.path.getsize(local) for local, _ in files)
|
||
db = None
|
||
if db_enabled:
|
||
db = db_config(load_credentials(CRED_FILE))
|
||
|
||
print(f'Backup: {backup_dir}')
|
||
if files_enabled:
|
||
print(f'Dateien: {len(files)}, {total_bytes / 1024 / 1024:.1f} MB -> {REMOTE_BASE}/')
|
||
if db:
|
||
action = 'droppen und neu importieren' if args.drop_db else 'importieren'
|
||
print(f'Datenbank: {dump_path} -> {db["host"]}/{db["database"]} ({action})')
|
||
|
||
if args.dry_run:
|
||
for _, rel in files:
|
||
print('DRY-RUN Datei ' + rel)
|
||
if db:
|
||
print('DRY-RUN Datenbank ' + db['database'])
|
||
return 0
|
||
|
||
if not args.yes:
|
||
warnings = []
|
||
if files_enabled:
|
||
warnings.append('Bestehende Dateien auf dem Server werden überschrieben.')
|
||
if db:
|
||
warnings.append(f'Die Datenbank {db["database"]} wird überschrieben.')
|
||
if args.drop_db:
|
||
warnings.append('Die Datenbank wird dabei komplett gelöscht und neu angelegt.')
|
||
answer = input(' '.join(warnings) + ' Fortfahren? [yes/NEIN] ')
|
||
if answer.strip().lower() not in ('yes', 'ja', 'y'):
|
||
print('Abgebrochen.')
|
||
return 1
|
||
|
||
if files_enabled:
|
||
creds = load_credentials(CRED_FILE)
|
||
try:
|
||
restore_files(creds, files)
|
||
except ftplib.all_errors as exc:
|
||
print('FTPS-Fehler: ' + str(exc), file=sys.stderr)
|
||
return 1
|
||
print(f'Dateien wiederhergestellt: {len(files)}')
|
||
|
||
if db:
|
||
try:
|
||
import_database(dump_path, db, args.drop_db)
|
||
except RuntimeError as exc:
|
||
print('DB-Fehler: ' + str(exc), file=sys.stderr)
|
||
return 1
|
||
print('Datenbank importiert.')
|
||
|
||
print()
|
||
print('Fertig.')
|
||
if files_enabled:
|
||
print('Bitte prüfen: Startseite, Login, ein Benutzerbild und eine Tourgalerie.')
|
||
return 0
|
||
|
||
|
||
if __name__ == '__main__':
|
||
sys.exit(main())
|