Backup und Wiederherstellung für Datenbank und Uploads ergänzen
This commit is contained in:
parent
c6e848d30b
commit
2f5fb5c2cc
5 changed files with 836 additions and 10 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,3 +1,4 @@
|
|||
__pycache__/
|
||||
*.pyc
|
||||
*.sql
|
||||
/backups/
|
||||
|
|
|
|||
90
DEPLOY.md
90
DEPLOY.md
|
|
@ -19,6 +19,96 @@ FTP_PASSWORD=...
|
|||
|
||||
Verbindung: **FTPS** (explizites TLS, Port 21), Remote-Basis: `/motorradig`.
|
||||
|
||||
## Backup und Wiederherstellung
|
||||
|
||||
Der DB-Dump allein reicht nicht: Benutzerbilder, Tourgalerien, PDFs und
|
||||
Mitgliedsanträge liegen ausschließlich auf dem Server unter
|
||||
`storage/img_storage/`. Tour-Titelbilder liegen unter `public/img/tour/`.
|
||||
Beides ist nicht in Git und wäre nach einem Neuaufsetzen verloren.
|
||||
|
||||
Vollständiges Backup (Datenbank + Dateien + Zugangsdaten/Keys):
|
||||
|
||||
```bash
|
||||
cd ~/repos/motorradig2027
|
||||
python3 tools/backup_motorradig.py
|
||||
```
|
||||
|
||||
Das Backup landet unter `backups/motorradig-backup-<Zeitstempel>/`:
|
||||
|
||||
```
|
||||
db/motorradig_<Zeitstempel>.sql Datenbank-Dump
|
||||
files/storage/img_storage/ Benutzerbilder, Galerien, PDFs, Anträge
|
||||
files/public/img/tour/ Tour-Titelbilder
|
||||
files/.env DB-Zugang und VAPID-Schlüssel
|
||||
files/storage/dkim/ privater DKIM-Schlüssel
|
||||
manifest.json Dateiliste mit Größen/SHA256 und Git-Commit
|
||||
```
|
||||
|
||||
Optionen:
|
||||
|
||||
- `--output <verzeichnis>` – anderes Zielverzeichnis
|
||||
- `--skip-db` / `--skip-media` – nur Teile sichern
|
||||
- `--no-secrets` – `.env` und DKIM-Schlüssel auslassen
|
||||
- `--with-logs` – zusätzlich `storage/logs` sichern
|
||||
- `--with-credentials` – lokale `.credentials` mitkopieren
|
||||
- `--dry-run` – nur anzeigen, was gesichert würde
|
||||
|
||||
Wichtig: Das Backup enthält personenbezogene Daten und private Schlüssel.
|
||||
`backups/` ist deshalb in `.gitignore` eingetragen. Das Verzeichnis wird mit
|
||||
Rechten `700` angelegt, die Dateien mit `600`. Zusätzlich eine verschlüsselte
|
||||
Kopie außerhalb des Rechners ablegen (z. B. `age`/`gpg` oder ein
|
||||
verschlüsseltes Backup-Ziel).
|
||||
|
||||
### Wiederherstellung
|
||||
|
||||
1. Code aus Git auf dem neuen Server ausrollen. Im `manifest.json` steht der
|
||||
Commit, von dem das Backup stammt (`source_commit`):
|
||||
|
||||
```bash
|
||||
git checkout <source_commit>
|
||||
python3 tools/deploy_motorradig.py --skip-media
|
||||
```
|
||||
2. Dateien und Datenbank zurückspielen:
|
||||
|
||||
```bash
|
||||
python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --with-db --dry-run
|
||||
python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --with-db
|
||||
```
|
||||
|
||||
Das Script prüft vorher die SHA256-Summen aus `manifest.json` und fragt
|
||||
vor dem Überschreiben nach. `.credentials` wird bewusst nicht hochgeladen.
|
||||
|
||||
Nur Dateien bzw. nur Datenbank:
|
||||
|
||||
```bash
|
||||
python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel>
|
||||
python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --db-only
|
||||
```
|
||||
|
||||
3. Der DB-Import läuft **nicht über FTP**, sondern direkt über den
|
||||
MySQL-Zugang aus `motorradig/.credentials` – genauso wie der Dump. Dafür
|
||||
sind weder Hosting-Panel noch SSH nötig. Verwendet werden `DB_HOST` (bzw.
|
||||
`FTP_URL`), `DB_USERNAME`, `DB_PASSWORD` und `DB_NAME` (bzw. `DB_USERNAME`).
|
||||
|
||||
Der Dump enthält `DROP TABLE`-Anweisungen; vorhandene Tabellen werden
|
||||
dadurch ersetzt. Soll die Datenbank vorher komplett gelöscht und neu
|
||||
angelegt werden – wie beim bisherigen Vorgehen –, zusätzlich `--drop-db`
|
||||
verwenden:
|
||||
|
||||
```bash
|
||||
python3 tools/restore_motorradig.py backups/motorradig-backup-<Zeitstempel> --db-only --drop-db
|
||||
```
|
||||
|
||||
Alternativ manuell mit dem MySQL-Client:
|
||||
|
||||
```bash
|
||||
mysql -h <DB_HOST> -u <DB_USERNAME> -p <DB_NAME> < db/motorradig_<Zeitstempel>.sql
|
||||
```
|
||||
|
||||
4. Prüfen: Startseite, Login, ein Benutzerbild und eine Tourgalerie.
|
||||
Falls sich DB-Zugangsdaten seit dem Backup geändert haben, `files/.env`
|
||||
auf dem Server entsprechend anpassen.
|
||||
|
||||
## Reguläres Deployment (alle App-Dateien)
|
||||
|
||||
```bash
|
||||
|
|
|
|||
370
tools/backup_motorradig.py
Executable file
370
tools/backup_motorradig.py
Executable file
|
|
@ -0,0 +1,370 @@
|
|||
#!/usr/bin/python3
|
||||
# Vollständiges Backup für motorradig2027: Datenbank + hochgeladene Dateien.
|
||||
#
|
||||
# Gesichert werden standardmäßig:
|
||||
# - Datenbank-Dump (mysqldump)
|
||||
# - storage/img_storage (Benutzerbilder, Tourgalerien, PDFs, Mitgliedsanträge)
|
||||
# - public/img/tour (Tour-Titelbilder)
|
||||
# - .env (DB-Zugang, VAPID-Schlüssel)
|
||||
# - storage/dkim (privater DKIM-Schlüssel)
|
||||
#
|
||||
# Nicht gesichert werden Code (liegt in Git) und Logs (nur mit --with-logs).
|
||||
#
|
||||
# Beispiele:
|
||||
# python3 tools/backup_motorradig.py
|
||||
# python3 tools/backup_motorradig.py --output /tmp/opencode
|
||||
# python3 tools/backup_motorradig.py --skip-media
|
||||
# python3 tools/backup_motorradig.py --no-secrets --with-logs
|
||||
#
|
||||
# Die Zugangsdaten werden aus ../motorradig/.credentials gelesen.
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import ftplib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
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'
|
||||
|
||||
# Uploads, die ausschließlich auf dem Server liegen.
|
||||
MEDIA_TARGETS = [
|
||||
'storage/img_storage',
|
||||
'public/img/tour',
|
||||
]
|
||||
|
||||
# Für einen Wiederaufbau benötigte Geheimnisse.
|
||||
SECRET_TARGETS = [
|
||||
'.env',
|
||||
'storage/dkim',
|
||||
]
|
||||
|
||||
LOG_TARGETS = [
|
||||
'storage/logs',
|
||||
]
|
||||
|
||||
|
||||
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'
|
||||
# Binärmodus, damit SIZE und Downloads zuverlässig funktionieren.
|
||||
ftp.voidcmd('TYPE I')
|
||||
return ftp
|
||||
|
||||
|
||||
def list_entries(ftp: ftplib.FTP, remote_path: str) -> list:
|
||||
"""Liefert [(name, typ, größe)] für ein Remote-Verzeichnis."""
|
||||
try:
|
||||
entries = []
|
||||
for name, facts in ftp.mlsd(remote_path):
|
||||
if name in ('.', '..'):
|
||||
continue
|
||||
kind = facts.get('type', 'file')
|
||||
size = int(facts.get('size', 0) or 0)
|
||||
entries.append((name, kind, size))
|
||||
return entries
|
||||
except ftplib.all_errors:
|
||||
# Fallback für Server ohne MLSD.
|
||||
entries = []
|
||||
for name in ftp.nlst(remote_path):
|
||||
base = name.rsplit('/', 1)[-1]
|
||||
if base in ('.', '..'):
|
||||
continue
|
||||
full = remote_path.rstrip('/') + '/' + base
|
||||
try:
|
||||
size = ftp.size(full)
|
||||
entries.append((base, 'file', size))
|
||||
except ftplib.all_errors:
|
||||
entries.append((base, 'dir', 0))
|
||||
return entries
|
||||
|
||||
|
||||
def collect_remote(ftp: ftplib.FTP, rel_path: str, out: list) -> None:
|
||||
"""Sammelt rekursiv (relativer Pfad, typ, größe) unterhalb von rel_path."""
|
||||
remote_path = REMOTE_BASE + '/' + rel_path
|
||||
try:
|
||||
entries = list_entries(ftp, remote_path)
|
||||
except ftplib.all_errors as exc:
|
||||
raise RuntimeError(f'{rel_path}: {exc}')
|
||||
|
||||
for name, kind, size in sorted(entries, key=lambda item: item[0]):
|
||||
child = rel_path.rstrip('/') + '/' + name
|
||||
if kind == 'dir':
|
||||
out.append((child, 'dir', 0))
|
||||
collect_remote(ftp, child, out)
|
||||
elif kind in ('file', 'OS.unix=slink'):
|
||||
out.append((child, 'file', size))
|
||||
|
||||
|
||||
def remote_file_size(ftp: ftplib.FTP, rel_path: str) -> int:
|
||||
"""Ermittelt die Dateigröße über MLSD, mit SIZE als Fallback."""
|
||||
remote = REMOTE_BASE + '/' + rel_path
|
||||
parent, name = remote.rsplit('/', 1)
|
||||
try:
|
||||
for entry, facts in ftp.mlsd(parent):
|
||||
if entry == name:
|
||||
return int(facts.get('size', 0) or 0)
|
||||
except ftplib.all_errors:
|
||||
pass
|
||||
|
||||
try:
|
||||
return ftp.size(remote)
|
||||
except ftplib.all_errors:
|
||||
return 0
|
||||
|
||||
|
||||
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 git_commit() -> str | None:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['git', '-C', REPO_ROOT, 'rev-parse', 'HEAD'],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
text=True,
|
||||
)
|
||||
return result.stdout.strip() or None
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return None
|
||||
|
||||
|
||||
def download(ftp: ftplib.FTP, rel_path: str, size: int, local_root: str) -> dict:
|
||||
remote = REMOTE_BASE + '/' + rel_path
|
||||
local = os.path.join(local_root, rel_path.replace('/', os.sep))
|
||||
os.makedirs(os.path.dirname(local), exist_ok=True)
|
||||
|
||||
with open(local, 'wb') as fh:
|
||||
ftp.retrbinary('RETR ' + remote, fh.write)
|
||||
os.chmod(local, 0o600)
|
||||
|
||||
local_size = os.path.getsize(local)
|
||||
if size and local_size != size:
|
||||
raise RuntimeError(f'Größenabweichung: erwartet {size} B, erhalten {local_size} B')
|
||||
|
||||
return {
|
||||
'path': rel_path,
|
||||
'size': local_size,
|
||||
'sha256': sha256(local),
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Vollständiges Backup (Datenbank + Uploads) von motorradig2027.',
|
||||
)
|
||||
parser.add_argument('--output', default=os.path.join(REPO_ROOT, 'backups'),
|
||||
help='Zielverzeichnis (Standard: <repo>/backups).')
|
||||
parser.add_argument('--label', default='', help='Optionaler Namenszusatz für das Backup-Verzeichnis.')
|
||||
parser.add_argument('--skip-db', action='store_true', help='Datenbank-Dump überspringen.')
|
||||
parser.add_argument('--skip-media', action='store_true', help='Uploads (img_storage, public/img/tour) überspringen.')
|
||||
parser.add_argument('--no-secrets', action='store_true', help='.env und DKIM-Schlüssel nicht sichern.')
|
||||
parser.add_argument('--with-logs', action='store_true', help='storage/logs mit sichern.')
|
||||
parser.add_argument('--with-credentials', action='store_true', help='Lokale .credentials mit ins Backup kopieren.')
|
||||
parser.add_argument('--dry-run', action='store_true', help='Nur auflisten, was gesichert würde.')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.skip_db and args.skip_media and args.no_secrets and not args.with_logs:
|
||||
print('Fehler: Es würde nichts gesichert werden.', file=sys.stderr)
|
||||
return 1
|
||||
|
||||
creds = load_credentials(CRED_FILE)
|
||||
|
||||
stamp = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
|
||||
label = re.sub(r'[^A-Za-z0-9._-]+', '-', args.label).strip('-')
|
||||
name = 'motorradig-backup-' + stamp + ('-' + label if label else '')
|
||||
backup_root = os.path.join(os.path.abspath(args.output), name)
|
||||
|
||||
targets = []
|
||||
if not args.skip_media:
|
||||
targets.extend(MEDIA_TARGETS)
|
||||
if not args.no_secrets:
|
||||
targets.extend(SECRET_TARGETS)
|
||||
if args.with_logs:
|
||||
targets.extend(LOG_TARGETS)
|
||||
|
||||
if args.dry_run:
|
||||
print('DRY-RUN: Ziel wäre ' + backup_root)
|
||||
if not args.skip_db:
|
||||
print(' DB-Dump')
|
||||
if not targets:
|
||||
return 0
|
||||
ftp = connect(creds)
|
||||
try:
|
||||
for rel_path in targets:
|
||||
remote_path = REMOTE_BASE + '/' + rel_path
|
||||
if rel_path == '.env':
|
||||
try:
|
||||
print(f' Datei {rel_path} ({remote_file_size(ftp, rel_path)} B)')
|
||||
except ftplib.all_errors as exc:
|
||||
print(f' FEHLER {rel_path}: {exc}')
|
||||
else:
|
||||
try:
|
||||
count = len(list_entries(ftp, remote_path))
|
||||
print(f' Verzeichnis {rel_path} ({count} Einträge)')
|
||||
except ftplib.all_errors as exc:
|
||||
print(f' FEHLER {rel_path}: {exc}')
|
||||
finally:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception:
|
||||
ftp.close()
|
||||
return 0
|
||||
|
||||
os.makedirs(backup_root, mode=0o700, exist_ok=True)
|
||||
os.chmod(backup_root, 0o700)
|
||||
print('Backup-Verzeichnis: ' + backup_root)
|
||||
|
||||
manifest = {
|
||||
'created_at': datetime.datetime.now().isoformat(timespec='seconds'),
|
||||
'source_commit': git_commit(),
|
||||
'remote_base': REMOTE_BASE,
|
||||
'database_dump': None,
|
||||
'database_dump_size': None,
|
||||
'database_dump_sha256': None,
|
||||
'files': [],
|
||||
'errors': [],
|
||||
}
|
||||
|
||||
# 1. Datenbank
|
||||
if not args.skip_db:
|
||||
try:
|
||||
from dump_motorradig import dump_database
|
||||
|
||||
db_dir = os.path.join(backup_root, 'db')
|
||||
dump_path = dump_database(db_dir, creds)
|
||||
os.chmod(db_dir, 0o700)
|
||||
os.chmod(dump_path, 0o600)
|
||||
manifest['database_dump'] = os.path.relpath(dump_path, backup_root)
|
||||
manifest['database_dump_size'] = os.path.getsize(dump_path)
|
||||
manifest['database_dump_sha256'] = sha256(dump_path)
|
||||
except Exception as exc:
|
||||
manifest['errors'].append('DB-Dump: ' + str(exc))
|
||||
print('FEHLER DB-Dump: ' + str(exc), file=sys.stderr)
|
||||
|
||||
# 2. Dateien per FTPS
|
||||
if targets:
|
||||
ftp = connect(creds)
|
||||
try:
|
||||
remote_files = []
|
||||
for rel_path in targets:
|
||||
if rel_path == '.env':
|
||||
try:
|
||||
size = remote_file_size(ftp, rel_path)
|
||||
remote_files.append((rel_path, 'file', size))
|
||||
except ftplib.all_errors as exc:
|
||||
manifest['errors'].append(f'{rel_path}: {exc}')
|
||||
print(f'FEHLER {rel_path}: {exc}', file=sys.stderr)
|
||||
continue
|
||||
|
||||
try:
|
||||
entries = list_entries(ftp, REMOTE_BASE + '/' + rel_path)
|
||||
except ftplib.all_errors as exc:
|
||||
manifest['errors'].append(f'{rel_path}: {exc}')
|
||||
print(f'FEHLER {rel_path}: {exc}', file=sys.stderr)
|
||||
continue
|
||||
del entries
|
||||
|
||||
remote_files.append((rel_path, 'dir', 0))
|
||||
try:
|
||||
collect_remote(ftp, rel_path, remote_files)
|
||||
except Exception as exc:
|
||||
manifest['errors'].append(str(exc))
|
||||
print(f'FEHLER {exc}', file=sys.stderr)
|
||||
|
||||
total = len([item for item in remote_files if item[1] == 'file'])
|
||||
print(f'{total} Datei(en) werden heruntergeladen …')
|
||||
|
||||
index = 0
|
||||
files_root = os.path.join(backup_root, 'files')
|
||||
for rel_path, kind, size in remote_files:
|
||||
local = os.path.join(files_root, rel_path.replace('/', os.sep))
|
||||
if kind == 'dir':
|
||||
os.makedirs(local, exist_ok=True)
|
||||
os.chmod(local, 0o700)
|
||||
continue
|
||||
|
||||
index += 1
|
||||
print(f'[{index}/{total}] {rel_path}')
|
||||
try:
|
||||
manifest['files'].append(download(ftp, rel_path, size, files_root))
|
||||
except Exception as exc:
|
||||
message = f'{rel_path}: {exc}'
|
||||
manifest['errors'].append(message)
|
||||
print(' FEHLER: ' + str(exc), file=sys.stderr)
|
||||
|
||||
if args.with_credentials and os.path.isfile(CRED_FILE):
|
||||
target = os.path.join(files_root, '.credentials')
|
||||
os.makedirs(files_root, exist_ok=True)
|
||||
shutil.copyfile(CRED_FILE, target)
|
||||
os.chmod(target, 0o600)
|
||||
manifest['files'].append({
|
||||
'path': '.credentials',
|
||||
'size': os.path.getsize(target),
|
||||
'sha256': sha256(target),
|
||||
})
|
||||
print('Lokal kopiert: .credentials')
|
||||
finally:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception:
|
||||
try:
|
||||
ftp.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3. Manifest
|
||||
manifest['total_bytes'] = sum(item['size'] for item in manifest['files'])
|
||||
manifest_path = os.path.join(backup_root, 'manifest.json')
|
||||
with open(manifest_path, 'w', encoding='utf-8') as fh:
|
||||
json.dump(manifest, fh, indent=2, ensure_ascii=False)
|
||||
fh.write('\n')
|
||||
os.chmod(manifest_path, 0o600)
|
||||
|
||||
print()
|
||||
print(f'Dateien: {len(manifest["files"])}, gesamt {manifest["total_bytes"] / 1024 / 1024:.1f} MB')
|
||||
if manifest['errors']:
|
||||
print(f'FEHLER: {len(manifest["errors"])} Datei(en) nicht gesichert (siehe manifest.json).', file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print('Fertig.')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
|
|
@ -2,7 +2,12 @@
|
|||
# DB-Dump für motorradig2027.
|
||||
# Voraussetzung: mysqldump muss installiert sein (apt install mysql-client).
|
||||
# Die Zugangsdaten werden aus ../motorradig/.credentials gelesen (KEY=VALUE).
|
||||
#
|
||||
# Beispiele:
|
||||
# python3 tools/dump_motorradig.py
|
||||
# python3 tools/dump_motorradig.py --output /tmp/opencode
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import os
|
||||
import subprocess
|
||||
|
|
@ -31,8 +36,10 @@ def load_credentials(path: str) -> dict:
|
|||
return creds
|
||||
|
||||
|
||||
def main() -> int:
|
||||
creds = load_credentials(CRED_FILE)
|
||||
def dump_database(output_dir: str = '.', creds: dict | None = None) -> str:
|
||||
"""Schreibt einen DB-Dump nach output_dir und gibt den Pfad zurück."""
|
||||
if creds is None:
|
||||
creds = load_credentials(CRED_FILE)
|
||||
|
||||
db_host = creds.get('DB_HOST', creds.get('FTP_URL', ''))
|
||||
db_user = creds.get('DB_USERNAME', '')
|
||||
|
|
@ -50,32 +57,53 @@ def main() -> int:
|
|||
missing.append('DB_NAME (oder DB_USERNAME)')
|
||||
|
||||
if missing:
|
||||
print('Fehler: Fehlende Credentials: ' + ', '.join(missing), file=sys.stderr)
|
||||
return 1
|
||||
raise RuntimeError('Fehlende Credentials: ' + ', '.join(missing))
|
||||
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
now = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
|
||||
filename = 'motorradig_' + now + '.sql'
|
||||
path = os.path.join(output_dir, 'motorradig_' + now + '.sql')
|
||||
|
||||
print(f'Dumping {filename} (Host: {db_host}, DB: {db_name})')
|
||||
print(f'Dumping {path} (Host: {db_host}, DB: {db_name})')
|
||||
|
||||
cmd = [
|
||||
'mysqldump',
|
||||
'--no-tablespaces',
|
||||
'--column-statistics=0',
|
||||
'--single-transaction',
|
||||
'--quick',
|
||||
'--user=' + db_user,
|
||||
'--password=' + db_password,
|
||||
'--host=' + db_host,
|
||||
db_name,
|
||||
]
|
||||
|
||||
with open(filename, 'w', encoding='utf-8') as out:
|
||||
with open(path, 'w', encoding='utf-8') as out:
|
||||
result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE)
|
||||
|
||||
if result.returncode != 0:
|
||||
print(result.stderr.decode('utf-8', 'replace'), file=sys.stderr)
|
||||
return result.returncode
|
||||
# Unvollständigen Dump nicht liegen lassen.
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
raise RuntimeError(result.stderr.decode('utf-8', 'replace').strip())
|
||||
|
||||
print('Fertig.')
|
||||
return path
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description='Datenbank-Dump von motorradig2027 erzeugen.')
|
||||
parser.add_argument('--output', default='.', help='Zielverzeichnis für den Dump (Standard: aktuelles Verzeichnis).')
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
path = dump_database(args.output)
|
||||
except RuntimeError as exc:
|
||||
print('Fehler: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print('Fertig: ' + path)
|
||||
return 0
|
||||
|
||||
|
||||
|
|
|
|||
337
tools/restore_motorradig.py
Executable file
337
tools/restore_motorradig.py
Executable file
|
|
@ -0,0 +1,337 @@
|
|||
#!/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
|
||||
|
||||
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())
|
||||
Loading…
Add table
Add a link
Reference in a new issue