- scripts/migrate_matrix_to_postgres.sh : port complet dans un conteneur PG dédié, reprenable, vérifications préalables et post-port intégrées - scripts/verify_migration.sh : comptages SQLite/PG, FK, chaîne refresh_tokens, séquences, smoke test Synapse jetable - scripts/synapse_port_db_fixed.py : script officiel synapse_port_db (v1.162.0) patché — FK auto-référentes refresh_tokens, séquence un_partial_stated_room_stream_sequence, purge stream_positions à la reprise - scripts/switch_database.py : bascule idempotente du homeserver.yaml avec backup de rollback - examples/ : stack compose PostgreSQL (collation C), bloc database, backup à chaud pg_dump -Fc + rotation - docs/ : guide détaillé en 7 étapes (prérequis, snapshot, migration, vérifications, bascule, rollback, après-migration) Éprouvé en production : ~30 Go SQLite, 162 tables, port 2h50, zéro perte.
134 lines
4.5 KiB
Python
Executable File
134 lines
4.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Bascule le bloc `database` de homeserver.yaml de sqlite3 vers psycopg2.
|
|
|
|
Remplace le bloc :
|
|
database:
|
|
name: sqlite3
|
|
args:
|
|
database: /data/homeserver.db
|
|
... (toutes les lignes indentées suivantes)
|
|
par un bloc psycopg2 pointant vers le serveur PostgreSQL de votre choix.
|
|
|
|
- Idempotent : ne fait rien si psycopg2 est déjà configuré.
|
|
- Crée un backup du fichier avant modification (une seule fois, pour garder
|
|
un point de rollback SQLite) : <fichier>.sqlite-backup
|
|
- Le mot de passe n'est jamais passé en argument de processus (visible dans
|
|
`ps`) : variable d'environnement SYNAPSE_PG_PASSWORD, ou prompt.
|
|
|
|
Exemple :
|
|
SYNAPSE_PG_PASSWORD='secret' python3 switch_database.py \\
|
|
--homeserver-yaml /data/homeserver.yaml \\
|
|
--pg-host synapse-database --pg-user synapse --pg-database synapse
|
|
"""
|
|
|
|
import argparse
|
|
import getpass
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
|
|
def build_pg_block(args: argparse.Namespace, password: str) -> str:
|
|
quoted = password.replace("\\", "\\\\").replace('"', '\\"')
|
|
lines = [
|
|
"database:",
|
|
" name: psycopg2",
|
|
" args:",
|
|
f" user: {args.pg_user}",
|
|
f' password: "{quoted}"',
|
|
f" database: {args.pg_database}",
|
|
f" host: {args.pg_host}",
|
|
f" port: {args.pg_port}",
|
|
" cp_min: 5",
|
|
" cp_max: 10",
|
|
]
|
|
if not args.no_keepalives:
|
|
lines += [
|
|
" keepalives_idle: 10",
|
|
" keepalives_interval: 10",
|
|
" keepalives_count: 3",
|
|
]
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def find_sqlite_block(text: str) -> tuple[int, int] | None:
|
|
"""Localise le bloc `database:` sqlite3 (début inclus, fin exclue)."""
|
|
lines = text.splitlines(keepends=True)
|
|
for i, line in enumerate(lines):
|
|
if line.rstrip("\r\n") != "database:":
|
|
continue
|
|
if i + 1 >= len(lines) or not re.match(r"^\s+name:\s*sqlite3\s*$", lines[i + 1]):
|
|
continue
|
|
j = i + 2
|
|
# Consomme l'indenté et les lignes vides, s'arrête à la prochaine clé
|
|
# de premier niveau.
|
|
while j < len(lines) and (lines[j].strip() == "" or lines[j][:1] in (" ", "\t")):
|
|
j += 1
|
|
return i, j
|
|
return None
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--homeserver-yaml", required=True, help="chemin du homeserver.yaml")
|
|
parser.add_argument("--pg-host", required=True, help="hôte PostgreSQL (nom du conteneur/service)")
|
|
parser.add_argument("--pg-port", default=5432, type=int, help="port PostgreSQL (défaut: 5432)")
|
|
parser.add_argument("--pg-user", required=True, help="utilisateur PostgreSQL")
|
|
parser.add_argument("--pg-database", required=True, help="base PostgreSQL")
|
|
parser.add_argument("--backup", help="chemin du backup (défaut: <yaml>.sqlite-backup)")
|
|
parser.add_argument("--no-keepalives", action="store_true", help="ne pas ajouter les options keepalives")
|
|
parser.add_argument("--dry-run", action="store_true", help="affiche le résultat sans écrire")
|
|
args = parser.parse_args()
|
|
|
|
path = args.homeserver_yaml
|
|
if not os.path.isfile(path):
|
|
print(f"ERREUR: fichier introuvable: {path}", file=sys.stderr)
|
|
return 1
|
|
with open(path, encoding="utf-8") as f:
|
|
src = f.read()
|
|
|
|
if re.search(r"^\s+name:\s*psycopg2\s*$", src, re.MULTILINE):
|
|
print("DÉJÀ BASCULÉ (psycopg2 présent dans le fichier), rien à faire.")
|
|
return 0
|
|
|
|
block = find_sqlite_block(src)
|
|
if block is None:
|
|
print("ERREUR: bloc `database:` / `name: sqlite3` introuvable dans le fichier.", file=sys.stderr)
|
|
return 1
|
|
|
|
password = os.environ.get("SYNAPSE_PG_PASSWORD") or getpass.getprompt(
|
|
f"Mot de passe PostgreSQL pour {args.pg_user}@{args.pg_host}: "
|
|
)
|
|
if not password:
|
|
print("ERREUR: mot de passe vide.", file=sys.stderr)
|
|
return 1
|
|
|
|
pg_block = build_pg_block(args, password)
|
|
lines = src.splitlines(keepends=True)
|
|
start, end = block
|
|
new_text = "".join(lines[:start]) + pg_block + "".join(lines[end:])
|
|
|
|
if args.dry_run:
|
|
print("--- APERÇU du nouveau bloc ---")
|
|
print(pg_block, end="")
|
|
return 0
|
|
|
|
backup = args.backup or f"{path}.sqlite-backup"
|
|
if not os.path.exists(backup):
|
|
with open(backup, "w", encoding="utf-8") as f:
|
|
f.write(src)
|
|
print(f"Backup créé : {backup}")
|
|
else:
|
|
print(f"Backup existant conservé : {backup}")
|
|
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
f.write(new_text)
|
|
print(f"{path} basculé sur psycopg2 ({args.pg_user}@{args.pg_host}:{args.pg_port}/{args.pg_database})")
|
|
print("Rappel : la base PostgreSQL doit être joignable depuis le conteneur Synapse")
|
|
print("au démarrage (réseau docker partagé), et démarrée AVANT Synapse.")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|