Premier commit

Cette révision appartient à :
Théo Gastinel a révisé 2026-10-11 01:57:24 +02:00
révision 43ac041278
6 fichiers modifiés
+705

Aucun fichier ne correspond à votre recherche

+66
Voir le fichier
@@ -0,0 +1,66 @@
# --- double-push : exclusions generiques (secrets, builds, binaires, gros fichiers) ---
target/
node_modules/
build/
build-*/
dist/
out/
.gradle/
.idea/
venv/
.venv/
env/
__pycache__/
*.pyc
.cache/
.next/
.env
.env.*
!.env.example
accounts.json
Clee.API/
*.pem
*.key
*.p12
*.pfx
*.jks
*.keystore
keystore.properties
id_rsa*
id_ed25519*
*.kdbx
*.odt
*.sqlite
*.sqlite3
*.db
*.log
*.exe
*.dll
*.msi
*.jar
*.zip
*.7z
*.rar
*.tar
*.tar.gz
*.tgz
*.gguf
*.safetensors
*.onnx
*.pt
*.pth
*.bin
*.iso
*.gws
*.apk
*.aab
*.so
*.o
*.a
*.lib
*.pdb
*.mp4
*.mkv
*.wav
*.flac
+47
Voir le fichier
@@ -0,0 +1,47 @@
# Migration d'UUID (totoche10)
Script : `migrer-uuid.py` (Python 3 stdlib, NBT lu/écrit à la main) + `retour.sh`.
Sur le serveur : `~/staging/migration-uuid/` (copie de test dans `copie/`, marquée par le fichier `COPIE-MIGRATION`).
| UUID | Origine |
|---|---|
| `25b71084-eb1b-4988-8cfe-458026f7e514` | Microsoft (online-mode=true, données jusqu'au 09/10 21:20) |
| `e1769fd1-91f1-377b-b2ac-999a4a7c9c9e` | hors-ligne `OfflinePlayer:totoche10` (données depuis le 09/10) |
## Quand l'utiliser
**Uniquement** au moment de repasser en `online-mode=true` (ou l'inverse), **serveur ARRÊTÉ**, **avec le feu vert de Théo**.
Ne jamais lancer `--appliquer` serveur en marche : le serveur réécrirait playerdata/claims à l'arrêt.
## Ce qui est traité
ops.json, whitelist.json, usercache.json, usernamecache.json, banned-players.json (doublons retirés),
`neW512/gastineltpa-homes.json`, tous les `neW512/data/*.dat` contenant l'UUID (dont `gastinelclaims.dat` :
18 `owner` = 17 claims + 1 liste d'amis), `playerdata/*.dat|.dat_old`, `advancements`, `stats`, `skinrestorer`.
UUID reconnus sous forme int[4], chaîne, clé de compound et paires `…Most/…Least`.
Non traité : régions `.mca` (entités apprivoisées/propriétaires dans le monde), autres mods (gravestone, etc.).
## Playerdata
- `--garder les-deux` (défaut) : l'inventaire de l'UUID **source** gagne ; l'ancien fichier de l'UUID cible
et le fichier source sont conservés en `<uuid>.dat.avant-migration`.
- `--garder source` : idem (la source gagne).
- `--garder cible` : l'inventaire déjà présent sous l'UUID d'arrivée gagne (ex. en `--vers-microsoft`, l'ancien
inventaire Microsoft du 09/10 plutôt que le récent hors-ligne).
## Commandes
```bash
cd ~/staging/migration-uuid
D=~/server-infra/stacks/minecraft-neoforge/data
python3 migrer-uuid.py --dossier "$D" --vers-microsoft # À BLANC (défaut) : n'écrit rien, OK serveur en marche
# le jour J, serveur arrêté + feu vert :
python3 migrer-uuid.py --dossier "$D" --vers-microsoft --appliquer --serveur-arrete-confirme
bash retour.sh "$D" "$D/sauvegarde-migration-AAAAMMJJ-HHMMSS" # retour arrière
```
`--appliquer` refuse si `docker ps` montre `minecraft-neoforge` (ou si docker ne répond pas), et refuse un dossier
qui n'est pas une copie sans `--serveur-arrete-confirme`. Sauvegarde préalable dans `sauvegarde-migration-<date>/`
(+ `MANIFESTE.json` utilisé par `retour.sh`).
## PIÈGE : l'ami à pseudo spécial
La liste d'amis de totoche10 contient `e65f2350-…` = `OfflinePlayer:gabybou201` (sans guillemet).
Or le joueur se connecte réellement en `gabybou201"` (avec guillemet) → UUID hors-ligne `128c0f10-9643-37ff-941d-afa49cdb30ec`
(usercache du 10/10 00:28). **L'amitié actuelle ne vise donc pas le compte réellement utilisé.**
Le script ne touche pas aux UUID des amis. En repassant en online-mode, gabybou aura un 3ᵉ UUID (Microsoft, inconnu
ici) : il faudra refaire `/friend add` une fois qu'il s'est connecté, ou ajouter un mappage dédié après vérification.
+172
Voir le fichier
@@ -0,0 +1,172 @@
#!/bin/bash
# Déploiement des correctifs « pseudos avec guillemet » PENDANT l'arrêt de maintenance de Minecraft.
# GastinelClaims 1.1.1 + GastinelTpa 1.2.1 + correction de la liste d'amis de totoche10 (e65f2350 -> 128c0f10).
#
# Usage : appliquer-pendant-arret.sh [--a-blanc] [--retour]
# (sans option) : applique ; idempotent (relancé, il constate que tout est déjà en place).
# --a-blanc : vérifie tout, n'écrit rien.
# --retour : remet les anciens jars et la liste d'amis d'origine.
# Garde-fou : NE FAIT RIEN si le conteneur minecraft-neoforge n'est pas arrêté (ou si docker ne répond pas).
# Si une étape échoue pendant l'application, tout est restauré (retour automatique) et le code de sortie est 1.
# Ce script ne démarre ni n'arrête JAMAIS Minecraft.
set -u
ST="${PSEUDOS_ST:-$HOME/staging/deploiement-pseudos}" # PSEUDOS_ST : tests uniquement
MC="$HOME/server-infra/stacks/minecraft-neoforge"
D="${PSEUDOS_DATA:-$MC/data}" # PSEUDOS_DATA : uniquement pour les tests sur une copie
MODS="$D/mods"
JARS="$ST/jars"
LOG="$ST/appliquer.log"
SUF=".avant-pseudos"
MODE=appliquer
for a in "$@"; do
case "$a" in
--retour) MODE=retour ;;
--a-blanc) MODE=blanc ;;
*) echo "option inconnue : $a" >&2; exit 2 ;;
esac
done
mkdir -p "$ST"
log() { echo "$(date '+%F %T') [pseudos] $*" | tee -a "$LOG"; }
# ---- garde-fou : conteneur ARRÊTÉ (état connu et non-running)
etat=$(docker inspect -f '{{.State.Running}}' minecraft-neoforge 2>/dev/null) || etat="inconnu"
# Test sur une COPIE (dossier marqué COPIE-MIGRATION, jamais le vrai) : le garde-fou docker est contourné
if [ "${PSEUDOS_TEST_COPIE:-0}" = 1 ] && [ -f "$D/COPIE-MIGRATION" ]; then etat=false; fi
if [ "$etat" != "false" ]; then
log "Minecraft n'est pas arrêté (état : $etat) : je ne touche à rien."
exit 0
fi
MODIDS="gastinelclaims gastineltpa"
JAR_gastinelclaims="gastinelclaims-neoforge-1.21.1-1.1.1.jar"
JAR_gastineltpa="gastineltpa-neoforge-1.21.1-1.2.1.jar"
VER_gastinelclaims="1.1.1"
VER_gastineltpa="1.2.1"
# modId déclaré dans un jar (neoforge.mods.toml) -> affiche "modId version"
info_jar() {
python3 -I - "$1" <<'PY'
import re, sys, zipfile
try:
z = zipfile.ZipFile(sys.argv[1])
t = z.read("META-INF/neoforge.mods.toml").decode("utf-8", "replace")
mid = re.search(r'modId\s*=\s*"([^"]+)"', t)
ver = re.search(r'^version\s*=\s*"([^"]+)"', t, re.M)
print((mid.group(1) if mid else "?"), (ver.group(1) if ver else "?"))
except Exception as e:
print("? ?")
PY
}
hash_de() { sha256sum "$1" | cut -d' ' -f1; }
# ---- jars actifs (dans mods/, finissant par .jar) déclarant un modId donné
jars_du_modid() {
local want="$1" f
for f in "$MODS"/*.jar; do
[ -f "$f" ] || continue
set -- $(info_jar "$f")
[ "$1" = "$want" ] && echo "$f"
done
}
# ---- retour arrière
retour() {
log "RETOUR ARRIÈRE"
local m jar f
for m in $MODIDS; do
eval "jar=\$JAR_$m"
# retire le jar du correctif (seulement s'il est bien le nôtre)
if [ -f "$MODS/$jar" ] && [ "$(hash_de "$MODS/$jar")" = "$(grep " $jar\$" "$JARS/SHA256SUMS" | cut -d' ' -f1)" ]; then
rm -f "$MODS/$jar" && log "retiré $jar"
fi
# remet les anciens jars sauvegardés
for f in "$MODS"/${m}-neoforge-*.jar"$SUF"; do
[ -f "$f" ] || continue
mv -f "$f" "${f%$SUF}" && log "restauré ${f%$SUF}"
done
done
# liste d'amis : fichier de sauvegarde si le .dat n'a pas changé depuis, sinon mappage inverse
local dat="$D/neW512/data/gastinelclaims.dat"
if [ -f "$dat$SUF" ]; then
if [ -f "$ST/etat-hash-dat-apres" ] && [ "$(hash_de "$dat")" = "$(cat "$ST/etat-hash-dat-apres")" ]; then
cp -p "$dat$SUF" "$dat" && log "liste d'amis restaurée depuis la sauvegarde"
else
python3 -I "$ST/corriger-amis-gabybou.py" --dossier "$D" --appliquer --inverse >>"$LOG" 2>&1 \
&& log "liste d'amis : mappage inverse appliqué (le .dat avait changé)" \
|| log "ATTENTION : retour de la liste d'amis impossible automatiquement"
fi
fi
rm -f "$ST/etat-applique" "$ST/etat-hash-dat-apres"
log "retour terminé"
}
if [ "$MODE" = retour ]; then retour; exit 0; fi
# ---- vérifications préalables (rien n'est modifié ici)
echec=0
[ -d "$MODS" ] || { log "ERREUR : $MODS absent"; exit 1; }
[ -f "$JARS/SHA256SUMS" ] || { log "ERREUR : $JARS/SHA256SUMS absent"; exit 1; }
for m in $MODIDS; do
eval "jar=\$JAR_$m"; eval "ver=\$VER_$m"
src="$JARS/$jar"
if [ ! -s "$src" ]; then log "ERREUR : $src absent ou vide"; echec=1; continue; fi
attendu=$(grep " $jar\$" "$JARS/SHA256SUMS" | cut -d' ' -f1)
reel=$(hash_de "$src")
if [ -z "$attendu" ] || [ "$attendu" != "$reel" ]; then log "ERREUR : hash de $jar ($reel) différent de l'attendu ($attendu)"; echec=1; continue; fi
set -- $(info_jar "$src")
if [ "$1" != "$m" ] || [ "$2" != "$ver" ]; then log "ERREUR : $jar déclare modId=$1 version=$2 (attendu $m $ver)"; echec=1; continue; fi
log "jar OK : $jar ($(stat -c %s "$src") octets, sha256 ${reel:0:12}…)"
done
[ -f "$ST/corriger-amis-gabybou.py" ] && [ -f "$ST/migrer-uuid.py" ] || { log "ERREUR : script d'amis ou migrer-uuid.py absent dans $ST"; echec=1; }
[ -f "$D/neW512/data/gastinelclaims.dat" ] || { log "ERREUR : gastinelclaims.dat absent"; echec=1; }
[ $echec -eq 0 ] || { log "Vérifications en échec : rien modifié."; exit 1; }
if [ "$MODE" = blanc ]; then
for m in $MODIDS; do eval "jar=\$JAR_$m"; log "(à blanc) jars actifs du mod $m : $(jars_du_modid "$m" | tr '\n' ' ')-> $jar"; done
python3 -I "$ST/corriger-amis-gabybou.py" --dossier "$D" 2>&1 | tee -a "$LOG"
log "(à blanc) terminé, rien écrit."
exit 0
fi
# ---- application
fail() { log "ÉCHEC : $* -> retour arrière automatique"; retour; exit 1; }
for m in $MODIDS; do
eval "jar=\$JAR_$m"
src="$JARS/$jar"
# 1) anciens jars du même mod_id (quel que soit leur nom) : renommés en .avant-pseudos (jamais écrasés)
for old in $(jars_du_modid "$m"); do
[ "$(basename "$old")" = "$jar" ] && continue
if [ -e "$old$SUF" ]; then fail "sauvegarde $old$SUF déjà présente"; fi
mv "$old" "$old$SUF" || fail "renommage de $old"
log "ancien jar mis de côté : $(basename "$old")$SUF"
done
# 2) nouveau jar (copie atomique, mêmes droits que les autres)
if [ -f "$MODS/$jar" ] && [ "$(hash_de "$MODS/$jar")" = "$(hash_de "$src")" ]; then
log "$jar déjà en place (identique)"
else
if [ -f "$MODS/$jar" ]; then
[ -e "$MODS/$jar$SUF" ] && fail "sauvegarde $jar$SUF déjà présente"
mv "$MODS/$jar" "$MODS/$jar$SUF" || fail "mise de côté de $jar différent"
fi
cp "$src" "$MODS/.$jar.tmp" || fail "copie de $jar"
chmod 644 "$MODS/.$jar.tmp"
mv -f "$MODS/.$jar.tmp" "$MODS/$jar" || fail "mise en place de $jar"
[ "$(hash_de "$MODS/$jar")" = "$(hash_de "$src")" ] || fail "hash de $jar après copie"
log "installé : $jar"
fi
# 3) un seul jar actif pour ce mod_id
n=$(jars_du_modid "$m" | wc -l)
[ "$n" -eq 1 ] || fail "$n jars actifs pour le mod $m (attendu 1)"
done
# 4) liste d'amis
python3 -I "$ST/corriger-amis-gabybou.py" --dossier "$D" --appliquer >>"$LOG" 2>&1 || fail "correctif de la liste d'amis"
# hash du .dat juste après la correction (sert au retour) : seulement à la première application
[ -f "$ST/etat-applique" ] || hash_de "$D/neW512/data/gastinelclaims.dat" > "$ST/etat-hash-dat-apres"
log "liste d'amis vérifiée/corrigée"
date '+%F %T' > "$ST/etat-applique"
log "TERMINÉ : GastinelClaims 1.1.1, GastinelTpa 1.2.1, amis corrigés. Minecraft n'a pas été touché."
exit 0
+118
Voir le fichier
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Correctif dédié : dans la liste d'AMIS de totoche10, e65f2350-… (« gabybou201 » sans guillemet)
devient 128c0f10-… (« gabybou201" », le compte réellement utilisé). RIEN d'autre n'est modifié :
ni les claims (owner), ni les autres fichiers, ni les amis des autres joueurs.
Python 3 stdlib. Réutilise le lecteur/écrivain NBT de migrer-uuid.py (même dossier).
--dossier DIR racine des données (contient neW512/data/gastinelclaims.dat)
--appliquer écrit (défaut : À BLANC). Refuse si le conteneur minecraft-neoforge tourne,
sauf dossier marqué COPIE-MIGRATION.
--retour restaure gastinelclaims.dat depuis gastinelclaims.dat.avant-pseudos
--inverse applique le mappage inverse (sans toucher à la sauvegarde existante)
Idempotent : relancé après application, il ne trouve plus rien à faire.
Sauvegarde : <dat>.avant-pseudos (créée une seule fois, jamais écrasée).
"""
import argparse, importlib.util, os, shutil, subprocess, sys
PROP = "e1769fd1-91f1-377b-b2ac-999a4a7c9c9e" # totoche10 (hors-ligne)
ANCIEN = "e65f2350-d100-3a51-ae80-50fbcce624c0" # OfflinePlayer:gabybou201
NOUVEAU = "128c0f10-9643-37ff-941d-afa49cdb30ec" # OfflinePlayer:gabybou201"
CONTENEUR = "minecraft-neoforge"
def charger_nbt():
ici = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("migrer_uuid", os.path.join(ici, "migrer-uuid.py"))
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
return m
def serveur_en_ligne():
try:
r = subprocess.run(["docker", "ps", "--filter", "name=^%s$" % CONTENEUR, "--format", "{{.Names}}"],
capture_output=True, text=True, timeout=15)
if r.returncode != 0:
return True
return CONTENEUR in r.stdout
except Exception:
return True
def trouver_listes_amis(tag, out):
"""Toutes les entrées de listes nommées 'friends' (compound avec owner + friends)."""
if tag.t == 10:
for k, s in tag.v.items():
if k == "friends" and s.t == 9 and s.v[0] == 10:
for ent in s.v[1]:
out.append(ent)
trouver_listes_amis(s, out)
elif tag.t == 9:
for s in tag.v[1]:
trouver_listes_amis(s, out)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--dossier", required=True)
ap.add_argument("--appliquer", action="store_true")
ap.add_argument("--retour", action="store_true")
ap.add_argument("--inverse", action="store_true",
help="mappage inverse (128c0f10 -> e65f2350) : retour logique si le .dat a changé depuis")
a = ap.parse_args()
global ANCIEN, NOUVEAU
if a.inverse:
ANCIEN, NOUVEAU = NOUVEAU, ANCIEN
D = os.path.abspath(a.dossier)
dat = os.path.join(D, "neW512", "data", "gastinelclaims.dat")
bak = dat + ".avant-pseudos"
copie = os.path.exists(os.path.join(D, "COPIE-MIGRATION"))
if not os.path.exists(dat):
print("ERREUR : %s absent" % dat); return 2
if (a.appliquer or a.retour) and serveur_en_ligne() and not copie:
print("REFUS : Minecraft tourne (ou docker ne répond pas). Rien n'est modifié."); return 3
if a.retour:
if not os.path.exists(bak):
print("Rien à restaurer (%s absent)." % bak); return 0
shutil.copy2(bak, dat); print("Restauré :", dat); return 0
m = charger_nbt()
gz, nom, rac = m.lire_nbt(dat)
ents = []; trouver_listes_amis(rac, ents)
si, di, pi = m.u2ints(ANCIEN), m.u2ints(NOUVEAU), m.u2ints(PROP)
avant_claims = None
modifs = 0
for ent in ents:
d = ent.v
if "owner" not in d or d["owner"].t != 11 or d["owner"].v != pi:
continue
lst = d["friends"]; et, items = lst.v
valeurs = [it.v for it in items]
a_ancien = si in valeurs
a_nouveau = di in valeurs
print("amis de totoche10 : ancien=%s nouveau=%s (%d amis)" % (a_ancien, a_nouveau, len(items)))
if not a_ancien:
continue
nouveaux = []
for it in items:
if it.v == si:
if a_nouveau or any(n.v == di for n in nouveaux):
continue # le bon est déjà là : on retire seulement l'ancien
it.v = list(di)
nouveaux.append(it)
lst.v = (et, nouveaux); modifs += 1
if modifs == 0:
print("RIEN À FAIRE (déjà corrigé ou ancien UUID absent)."); return 0
if not a.appliquer:
print("À BLANC : 1 liste d'amis serait corrigée (%s -> %s). Rien écrit." % (ANCIEN, NOUVEAU)); return 0
if not os.path.exists(bak):
shutil.copy2(dat, bak)
m.ecrire_nbt(dat, gz, nom, rac)
print("APPLIQUÉ : %s -> %s dans les amis de totoche10. Sauvegarde : %s" % (ANCIEN, NOUVEAU, bak))
return 0
if __name__ == "__main__":
sys.exit(main())
+281
Voir le fichier
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Migration d'UUID d'un joueur (totoche10) entre UUID Microsoft et UUID hors-ligne.
Par défaut : À BLANC (rien n'est écrit). Python 3 stdlib uniquement (NBT lu/écrit à la main).
--vers-microsoft : e1769fd1-… (hors-ligne) -> 25b71084-… (Microsoft) [défaut]
--vers-horsligne : 25b71084-… -> e1769fd1-…
--dossier DIR : racine des données (contient ops.json, neW512/…). DOIT être une copie
sauf --appliquer --serveur-arrete-confirme sur le vrai dossier.
--garder {source,cible,les-deux} : quel playerdata devient celui de l'UUID cible
source = l'inventaire de l'UUID de départ gagne (ex. le récent hors-ligne en --vers-microsoft)
cible = l'inventaire déjà présent sous l'UUID d'arrivée gagne
les-deux = (défaut) la source gagne MAIS l'ancien fichier cible est conservé en
<uuid>.dat.avant-migration (rien n'est jamais perdu)
--appliquer : écrit. Refuse si le conteneur Minecraft tourne, si le dossier n'est pas
une copie (fichier COPIE-MIGRATION absent) sauf --serveur-arrete-confirme.
Sauvegarde d'abord tous les fichiers touchés dans <dossier>/sauvegarde-migration-<date>/.
"""
import argparse, gzip, io, json, os, shutil, struct, subprocess, sys, time, uuid as uuidlib
MS = "25b71084-eb1b-4988-8cfe-458026f7e514"
HL = "e1769fd1-91f1-377b-b2ac-999a4a7c9c9e"
MONDE = "neW512"
CONTENEUR = "minecraft-neoforge"
# ---------------------------------------------------------------- NBT minimal
class Tag:
__slots__ = ("t", "v")
def __init__(self, t, v): self.t, self.v = t, v
def _rs(f):
n = struct.unpack(">H", f.read(2))[0]
return f.read(n).decode("utf-8", "surrogatepass") # MUTF-8 approx (suffisant ici)
def _ws(f, s):
b = s.encode("utf-8", "surrogatepass"); f.write(struct.pack(">H", len(b))); f.write(b)
def lire_payload(f, t):
if t == 1: return struct.unpack(">b", f.read(1))[0]
if t == 2: return struct.unpack(">h", f.read(2))[0]
if t == 3: return struct.unpack(">i", f.read(4))[0]
if t == 4: return struct.unpack(">q", f.read(8))[0]
if t == 5: return struct.unpack(">f", f.read(4))[0]
if t == 6: return struct.unpack(">d", f.read(8))[0]
if t == 7: n = struct.unpack(">i", f.read(4))[0]; return bytearray(f.read(n))
if t == 8: return _rs(f)
if t == 9:
et = f.read(1)[0]; n = struct.unpack(">i", f.read(4))[0]
return (et, [Tag(et, lire_payload(f, et)) for _ in range(n)])
if t == 10:
d = {}
while True:
ct = f.read(1)[0]
if ct == 0: return d
nom = _rs(f); d[nom] = Tag(ct, lire_payload(f, ct))
if t == 11: n = struct.unpack(">i", f.read(4))[0]; return list(struct.unpack(">%di" % n, f.read(4 * n)))
if t == 12: n = struct.unpack(">i", f.read(4))[0]; return list(struct.unpack(">%dq" % n, f.read(8 * n)))
raise ValueError("tag NBT inconnu %r" % t)
def ecrire_payload(f, t, v):
if t == 1: f.write(struct.pack(">b", v))
elif t == 2: f.write(struct.pack(">h", v))
elif t == 3: f.write(struct.pack(">i", v))
elif t == 4: f.write(struct.pack(">q", v))
elif t == 5: f.write(struct.pack(">f", v))
elif t == 6: f.write(struct.pack(">d", v))
elif t == 7: f.write(struct.pack(">i", len(v))); f.write(bytes(v))
elif t == 8: _ws(f, v)
elif t == 9:
et, items = v; f.write(bytes([et])); f.write(struct.pack(">i", len(items)))
for it in items: ecrire_payload(f, et, it.v)
elif t == 10:
for nom, tg in v.items():
f.write(bytes([tg.t])); _ws(f, nom); ecrire_payload(f, tg.t, tg.v)
f.write(b"\x00")
elif t == 11: f.write(struct.pack(">i", len(v))); f.write(struct.pack(">%di" % len(v), *v))
elif t == 12: f.write(struct.pack(">i", len(v))); f.write(struct.pack(">%dq" % len(v), *v))
def lire_nbt(chemin):
brut = open(chemin, "rb").read()
gz = brut[:2] == b"\x1f\x8b"
if gz: brut = gzip.decompress(brut)
f = io.BytesIO(brut); t = f.read(1)[0]; nom = _rs(f)
return gz, nom, Tag(t, lire_payload(f, t))
def ecrire_nbt(chemin, gz, nom, racine):
f = io.BytesIO(); f.write(bytes([racine.t])); _ws(f, nom); ecrire_payload(f, racine.t, racine.v)
data = f.getvalue()
if gz: data = gzip.compress(data, mtime=0)
tmp = chemin + ".tmp-migration"; open(tmp, "wb").write(data); os.replace(tmp, chemin)
# représentations d'un UUID dans NBT
def u2ints(u):
b = uuidlib.UUID(u).bytes; return list(struct.unpack(">4i", b))
def u2longs(u):
b = uuidlib.UUID(u).bytes; return struct.unpack(">2q", b)
def remplacer_nbt(tag, src, dst, chemin, log):
"""Remplace src->dst sous toutes ses formes (int[4], string, Most/Least). Retourne nb."""
n = 0
si, di = u2ints(src), u2ints(dst); (sm, sl), (dm, dl) = u2longs(src), u2longs(dst)
if tag.t == 11 and tag.v == si:
tag.v = list(di); log.append(f"{chemin} : int[4] UUID"); return 1
if tag.t == 8 and src in tag.v:
log.append(f"{chemin} : chaîne {tag.v!r}"); tag.v = tag.v.replace(src, dst); return 1
if tag.t == 10:
d = tag.v
# paire xxxMost / xxxLeast
for k in list(d):
if k.endswith("Most") and d[k].t == 4 and d[k].v == sm:
kl = k[:-4] + "Least"
if kl in d and d[kl].v == sl:
d[k].v, d[kl].v = dm, dl; log.append(f"{chemin}.{k[:-4]} : Most/Least"); n += 1
# clés de compound égales à l'UUID
for k in list(d):
if src in k:
nk = k.replace(src, dst)
if nk in d: log.append(f"{chemin} : CONFLIT clé {nk} existe déjà (non fusionné)")
else:
d = {(nk if kk == k else kk): vv for kk, vv in d.items()}; tag.v = d
log.append(f"{chemin} : clé {k}"); n += 1
for k, sub in tag.v.items(): n += remplacer_nbt(sub, src, dst, f"{chemin}.{k}", log)
elif tag.t == 9:
for i, sub in enumerate(tag.v[1]): n += remplacer_nbt(sub, src, dst, f"{chemin}[{i}]", log)
return n
def compter_nbt(tag, u):
si = u2ints(u); m, l = u2longs(u); c = 0
if tag.t == 11 and tag.v == si: return 1
if tag.t == 8 and u in tag.v: return 1
if tag.t == 10:
for k, s in tag.v.items():
if u in k: c += 1
if k.endswith("Most") and s.t == 4 and s.v == m: c += 1
c += compter_nbt(s, u)
elif tag.t == 9:
for s in tag.v[1]: c += compter_nbt(s, u)
return c
# ---------------------------------------------------------------- JSON
def remplacer_json(obj, src, dst, chemin, log):
if isinstance(obj, dict):
res = {}
for k, v in obj.items():
nk = k
if src in k:
nk = k.replace(src, dst)
if nk in obj: log.append(f"{chemin} : CONFLIT clé {nk} déjà présente -> la source GAGNE, ancienne valeur loggée : {json.dumps(obj[nk], ensure_ascii=False)[:200]}")
else: log.append(f"{chemin} : clé {k} -> {nk}")
res[nk] = remplacer_json(v, src, dst, f"{chemin}.{nk}", log)
return res
if isinstance(obj, list):
out = [remplacer_json(v, src, dst, f"{chemin}[{i}]", log) for i, v in enumerate(obj)]
# dédoublonnage (ops/whitelist/usercache : même uuid deux fois après migration)
vus, dedup = set(), []
for e in out:
cle = json.dumps(e, sort_keys=True) if not isinstance(e, dict) else e.get("uuid", json.dumps(e, sort_keys=True))
if cle in vus: log.append(f"{chemin} : doublon retiré {json.dumps(e, ensure_ascii=False)}"); continue
vus.add(cle); dedup.append(e)
return dedup
if isinstance(obj, str) and src in obj:
log.append(f"{chemin} : valeur {obj!r}"); return obj.replace(src, dst)
return obj
# ---------------------------------------------------------------- plan
def serveur_en_ligne():
try:
r = subprocess.run(["docker", "ps", "--filter", f"name=^{CONTENEUR}$", "--format", "{{.Names}}"],
capture_output=True, text=True, timeout=15)
if r.returncode != 0: return True, "docker ps a échoué (prudence : considéré EN LIGNE)"
return (CONTENEUR in r.stdout), r.stdout.strip() or "aucun conteneur"
except Exception as e:
return True, f"docker indisponible ({e}) : considéré EN LIGNE"
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
g = ap.add_mutually_exclusive_group()
g.add_argument("--vers-microsoft", action="store_true")
g.add_argument("--vers-horsligne", action="store_true")
m = ap.add_mutually_exclusive_group()
m.add_argument("--a-blanc", action="store_true")
m.add_argument("--appliquer", action="store_true")
ap.add_argument("--dossier", required=True)
ap.add_argument("--garder", choices=["source", "cible", "les-deux"], default="les-deux")
ap.add_argument("--serveur-arrete-confirme", action="store_true",
help="autorise --appliquer sur un dossier qui n'est pas une copie (vrai monde, serveur ARRÊTÉ)")
ap.add_argument("--ignorer-docker", action="store_true", help="tests sur une machine sans le conteneur (copie uniquement)")
a = ap.parse_args()
src, dst = (MS, HL) if a.vers_horsligne else (HL, MS)
D = os.path.abspath(a.dossier); W = os.path.join(D, MONDE)
appliquer = a.appliquer
est_copie = os.path.exists(os.path.join(D, "COPIE-MIGRATION"))
print(f"== migration {src} -> {dst} dossier={D} mode={'APPLIQUER' if appliquer else 'À BLANC'} copie={est_copie} garder={a.garder}")
if appliquer:
enl, info = serveur_en_ligne()
if enl and not (a.ignorer_docker and est_copie):
sys.exit(f"REFUS : serveur Minecraft en ligne ou état inconnu ({info}). Arrêter le serveur d'abord.")
if not est_copie and not a.serveur_arrete_confirme:
sys.exit("REFUS : le dossier n'est pas une copie (fichier COPIE-MIGRATION absent). "
"Sur le vrai monde : serveur ARRÊTÉ + feu vert de Théo + --serveur-arrete-confirme.")
if os.path.exists(os.path.join(W, "session.lock")) and not est_copie:
print(" note : session.lock présent (normal même serveur arrêté) ; docker a confirmé l'arrêt.")
actions = [] # (type, chemin, fonction d'écriture)
touches = []
crees = []
# 1) JSON racine + homes + skinrestorer
jsons = [os.path.join(D, n) for n in ("ops.json", "whitelist.json", "usercache.json", "usernamecache.json", "banned-players.json")]
jsons.append(os.path.join(W, "gastineltpa-homes.json"))
for p in jsons:
if not os.path.exists(p): print(f"[absent] {os.path.relpath(p, D)}"); continue
obj = json.load(open(p, encoding="utf-8")); log = []
nouv = remplacer_json(obj, src, dst, os.path.basename(p), log)
if log:
print(f"[JSON] {os.path.relpath(p, D)} : {len(log)} changement(s)")
for l in log: print(" " + l)
touches.append(p)
actions.append(lambda p=p, nouv=nouv: open(p, "w", encoding="utf-8").write(json.dumps(nouv, indent=2, ensure_ascii=False) + "\n"))
else: print(f"[JSON] {os.path.relpath(p, D)} : rien")
# 2) NBT data/ (claims, amis…) — tous les .dat de data/ contenant l'UUID
ddir = os.path.join(W, "data")
for n in sorted(os.listdir(ddir)) if os.path.isdir(ddir) else []:
p = os.path.join(ddir, n)
if not n.endswith(".dat") or os.path.getsize(p) > 20_000_000: continue
try: gz, nom, rac = lire_nbt(p)
except Exception as e: print(f"[NBT] data/{n} illisible ({e}) ignoré"); continue
if compter_nbt(rac, src) == 0: continue
log = []; k = remplacer_nbt(rac, src, dst, n, log)
print(f"[NBT] data/{n} : {k} remplacement(s) ; occurrences restantes de la cible déjà présente : {compter_nbt(rac, dst) - k}")
for l in log: print(" " + l)
touches.append(p)
actions.append(lambda p=p, gz=gz, nom=nom, rac=rac: ecrire_nbt(p, gz, nom, rac))
# 3) fichiers par joueur : playerdata / advancements / stats / skinrestorer
for sous, ext in (("playerdata", ".dat"), ("playerdata", ".dat_old"), ("advancements", ".json"), ("stats", ".json"), ("skinrestorer", ".json")):
ps, pd = os.path.join(W, sous, src + ext), os.path.join(W, sous, dst + ext)
if not os.path.exists(ps): continue
cible_existe = os.path.exists(pd)
gagnant = "cible" if (a.garder == "cible" and cible_existe) else "source"
desc = f"[{sous}] {src}{ext} ({os.path.getsize(ps)} o, {time.strftime('%d/%m %H:%M', time.localtime(os.path.getmtime(ps)))})"
if cible_existe:
desc += f" vs cible existante ({os.path.getsize(pd)} o, {time.strftime('%d/%m %H:%M', time.localtime(os.path.getmtime(pd)))})"
print(f"{desc} -> gagnant : {gagnant}; ancienne(s) version(s) gardée(s) en .avant-migration")
touches += [ps] + ([pd] if cible_existe else [])
if not cible_existe: crees.append(pd)
def act(ps=ps, pd=pd, cible_existe=cible_existe, gagnant=gagnant, ext=ext):
if cible_existe and not os.path.exists(pd + ".avant-migration"): shutil.copy2(pd, pd + ".avant-migration")
if not os.path.exists(ps + ".avant-migration"): shutil.copy2(ps, ps + ".avant-migration")
if gagnant == "source":
shutil.copy2(ps, pd)
if ext.startswith(".dat"): # corriger un éventuel UUID interne
try:
gz, nom, rac = lire_nbt(pd); lg = []
if remplacer_nbt(rac, src, dst, "", lg): ecrire_nbt(pd, gz, nom, rac)
except Exception: pass
os.remove(ps) # la source est conservée en .avant-migration
actions.append(act)
if not actions:
print("== RIEN À FAIRE (déjà migré ? idempotent)"); return 0
if not appliquer:
print(f"== À BLANC : {len(actions)} action(s), {len(touches)} fichier(s) seraient touchés. Rien écrit."); return 0
sv = os.path.join(D, "sauvegarde-migration-" + time.strftime("%Y%m%d-%H%M%S"))
for p in touches:
rel = os.path.relpath(p, D); os.makedirs(os.path.dirname(os.path.join(sv, rel)), exist_ok=True)
shutil.copy2(p, os.path.join(sv, rel))
json.dump({"src": src, "dst": dst, "fichiers": [os.path.relpath(p, D) for p in touches],
"crees": [os.path.relpath(p, D) for p in crees]},
open(os.path.join(sv, "MANIFESTE.json"), "w"), indent=2)
print(f"== sauvegarde : {sv} ({len(touches)} fichiers)")
for f in actions: f()
print("== APPLIQUÉ. Retour arrière : retour.sh " + sv)
return 0
if __name__ == "__main__":
sys.exit(main())
+21
Voir le fichier
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Retour arrière d'une migration : retour.sh <dossier-données> <dossier sauvegarde-migration-…>
set -euo pipefail
D=$(realpath "$1"); S=$(realpath "$2")
[ -f "$S/MANIFESTE.json" ] || { echo "MANIFESTE.json absent dans $S"; exit 1; }
if docker ps --format '{{.Names}}' 2>/dev/null | grep -qx minecraft-neoforge && [ ! -f "$D/COPIE-MIGRATION" ]; then
echo "REFUS : serveur en ligne"; exit 1; fi
python3 - "$D" "$S" <<'PY'
import json,os,shutil,sys
D,S=sys.argv[1:]; m=json.load(open(os.path.join(S,"MANIFESTE.json")))
for r in m.get("crees",[]):
p=os.path.join(D,r)
if os.path.exists(p): os.remove(p); print("supprimé (créé par migration)",r)
for r in m["fichiers"]:
shutil.copy2(os.path.join(S,r),os.path.join(D,r)); print("restauré",r)
if os.path.exists(os.path.join(D,r)+".avant-migration"): os.remove(os.path.join(D,r)+".avant-migration")
for r in m.get("crees",[]):
a=os.path.join(D,r)+".avant-migration"
if os.path.exists(a): os.remove(a)
PY
echo "Retour arrière terminé."