"""betrieb/sicherung.py (29.11.): Live-Daten ausserhalb des Repos sichern - nur anhaengen, Versatz, Wiederaufnahme, nie leeren. Rein: Temp-Ordner als Quelle und Ziel, kein Client, kein Laeufer, kein Netz, keine Meldung (PF_DATEN_STILL=1).""" import gzip import json import os import sys import tempfile import zipfile sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "betrieb")) os.environ["PF_DATEN_STILL"] = "1" import sicherung as S wurzel = tempfile.mkdtemp(prefix="sicherung-") baum = os.path.join(wurzel, "livebaum") lauf = os.path.join(baum, "archiv", "lauf") scratch = os.path.join(baum, "sicht", "scratch") logs = os.path.join(wurzel, "clientlogs") ziel = os.path.join(wurzel, "pf-daten") for o in (lauf, scratch, logs, ziel): os.makedirs(o, exist_ok=True) zl = os.path.join(ziel, "livebaum", "lauf") meldungen = [] frei = {"b": 100 << 30} platz = S.Platz(ziel, min_gb=3, frei=lambda p: frei["b"], melden=lambda t, x: meldungen.append(t)) def schreib(p, text, modus="a"): with open(p, modus, encoding="utf-8", newline="\n") as f: f.write(text) def lies(p): with open(p, encoding="utf-8") as f: return f.read() def gang(stand, **kw): return S.durchgang(ziel, lauf, scratch, logs, stand, platz, faellig=kw.get("faellig", {"log", "lauf", "stand"})) # --- Anhang: nur ganze Zeilen, ab Versatz ------------------------------------------------------------------------------- h = os.path.join(lauf, "haende.jsonl") schreib(h, '{"hand": "1"}\n{"hand": "2"}\n{"hand": "3', "w") # dritte Zeile halb geschrieben schreib(os.path.join(scratch, "laeufer.txt"), "20:50:45 FOLD\n", "w") stand = {} b = gang(stand) assert lies(os.path.join(zl, "haende.jsonl")) == '{"hand": "1"}\n{"hand": "2"}\n', "halbe Zeile wartet" assert lies(os.path.join(zl, "laeufer.txt")) == "20:50:45 FOLD\n" assert stand["anhang"]["lauf/haende.jsonl"]["von"] == 28 schreib(h, '"}\n{"hand": "4"}\n') gang(stand) assert lies(os.path.join(zl, "haende.jsonl")) == '{"hand": "1"}\n{"hand": "2"}\n{"hand": "3"}\n{"hand": "4"}\n' gang(stand) # nichts Neues: nichts doppelt assert lies(os.path.join(zl, "haende.jsonl")).count('"hand"') == 4 # --- Wiederaufnahme aus stand.json (neuer Prozess) ---------------------------------------------------------------------- schreib(h, '{"hand": "5"}\n') stand2 = S.stand_lesen(ziel) assert stand2["anhang"]["lauf/haende.jsonl"]["von"] == stand["anhang"]["lauf/haende.jsonl"]["von"] gang(stand2) assert lies(os.path.join(zl, "haende.jsonl")).count('"hand"') == 5 # --- Absturz nach dem Anhang, vor stand.json: Ueberhang wird erkannt, keine Doppelzeilen --------------------------------- schreib(h, '{"hand": "6"}\n') alt = json.loads(json.dumps(S.stand_lesen(ziel))) # Stand VOR dem Durchgang gang(stand2) assert lies(os.path.join(zl, "haende.jsonl")).count('"hand"') == 6 schreib(h, '{"hand": "7"}\n') gang(alt) # wie nach Absturz: alter Versatz, Ziel schon weiter t = lies(os.path.join(zl, "haende.jsonl")) assert t.count('"hand": "6"') == 1 and t.count('"hand"') == 7, t assert "Ueberhang nach Absturz" in lies(os.path.join(ziel, "sicherung.log")) # --- Quelle neu angelegt (geleert/ersetzt): alte Kopie bleibt ganz, neue Generation --------------------------------------- vorher = lies(os.path.join(zl, "haende.jsonl")) schreib(h, '{"hand": "neu1"}\n', "w") gang(alt) assert lies(os.path.join(zl, "haende.jsonl")) == vorher, "alte Kopie nie geleert" gen = [n for n in os.listdir(zl) if n.startswith("haende.g")] assert len(gen) == 1 and lies(os.path.join(zl, gen[0])) == '{"hand": "neu1"}\n', gen # gleich lang, anderer Kopf (z. B. von Hand ersetzt): ebenfalls neue Generation schreib(h, '{"hand": "NEU1"}\n', "w") import time as _t _t.sleep(1.1) gang(alt) assert len([n for n in os.listdir(zl) if n.startswith("haende.g")]) == 2 # --- Zielkopie von aussen gekuerzt: nicht reparieren, nichts leeren, neu beginnen ----------------------------------------- _t.sleep(1.1) e = alt["anhang"]["lauf/haende.jsonl"] with open(e["ziel"], "r+b") as f: f.truncate(3) schreib(h, '{"hand": "x"}\n') gang(alt) assert os.path.getsize(os.path.join(zl, gen[0])) > 0 assert len([n for n in os.listdir(zl) if n.startswith("haende.g")]) == 3 # --- nie leeren: alle Zieldateien wachsen nur --------------------------------------------------------------------------- groessen = {n: os.path.getsize(os.path.join(zl, n)) for n in os.listdir(zl)} schreib(h, '{"hand": "y"}\n') schreib(os.path.join(lauf, "zuege.jsonl"), '{"hand": "y", "aktion": "FOLD"}\n') gang(alt) for n, g in groessen.items(): assert os.path.getsize(os.path.join(zl, n)) >= g, n assert lies(os.path.join(zl, "zuege.jsonl")).count("FOLD") == 1 # --- Platz < 3 GB: Pause, EINE Meldung, nichts geschrieben; danach weiter ---------------------------------------------- frei["b"] = 2 << 30 g = os.path.getsize(os.path.join(zl, "zuege.jsonl")) schreib(os.path.join(lauf, "zuege.jsonl"), '{"hand": "z"}\n') assert gang(alt) == {"pause": True} and gang(alt) == {"pause": True} assert len(meldungen) == 1 and os.path.getsize(os.path.join(zl, "zuege.jsonl")) == g assert "pausiert" in lies(os.path.join(ziel, "MELDUNG.txt")) frei["b"] = 100 << 30 gang(alt) assert lies(os.path.join(zl, "zuege.jsonl")).count('"hand": "z"') == 1 and len(meldungen) == 1 # --- Schnappschuss *.json: neu nur bei geaendertem Inhalt --------------------------------------------------------------- schreib(os.path.join(lauf, "zaehler.json"), '{"a": 1}', "w") gang(alt, faellig={"stand"}) gang(alt, faellig={"stand"}) so = os.path.join(ziel, "livebaum", "stand", "zaehler.json") assert len(os.listdir(so)) == 1 _t.sleep(1.1) schreib(os.path.join(lauf, "zaehler.json"), '{"a": 2}', "w") gang(alt, faellig={"stand"}) assert len(os.listdir(so)) == 2 assert sorted(gzip.decompress(open(os.path.join(so, n), "rb").read()) for n in os.listdir(so)) == [b'{"a": 1}', b'{"a": 2}'] # --- Client-Logs: Rotationen einmal je Inhalt, main.log laufend als gzip-Glieder ------------------------------------------ def rot(n, text): with open(os.path.join(logs, "main.%d.log.gz" % n), "wb") as f: f.write(gzip.compress(text.encode())) rot(1, "rotation A\n") schreib(os.path.join(logs, "main.log"), "zeile 1\nzeile 2\nhal", "w") gang(alt, faellig={"log"}) co = os.path.join(ziel, "clientlog") os.replace(os.path.join(logs, "main.1.log.gz"), os.path.join(logs, "main.2.log.gz")) # Rotation schiebt weiter rot(1, "rotation B\n") schreib(os.path.join(logs, "main.log"), "b\nzeile 3\n") gang(alt, faellig={"log"}) rots = sorted(n for n in os.listdir(co) if "laufend" not in n and n.endswith(".log.gz")) assert len(rots) == 2, rots # A nur einmal, obwohl umbenannt lf = [n for n in os.listdir(co) if "laufend" in n] assert len(lf) == 1 and gzip.open(os.path.join(co, lf[0]), "rt").read() == "zeile 1\nzeile 2\nhalb\nzeile 3\n" _t.sleep(1.1) schreib(os.path.join(logs, "main.log"), "nach rotation\n", "w") # main.log neu: neue laufende Datei, alte bleibt gang(alt, faellig={"log"}) lf2 = sorted(n for n in os.listdir(co) if "laufend" in n) assert len(lf2) == 2 and gzip.open(os.path.join(co, lf[0]), "rt").read().endswith("zeile 3\n") # Absturz mitten im gzip-Glied: halbes Glied wird nicht als erledigt gezaehlt, neue Datei, alte unangetastet e = alt["clientlog"]["laufend"] with open(e["ziel"], "ab") as f: f.write(gzip.compress(b"xx")[:7]) schreib(os.path.join(logs, "main.log"), "weiter\n") _t.sleep(1.1) gang(alt, faellig={"log"}) assert len([n for n in os.listdir(co) if "laufend" in n]) == 3 # --- Tages-Zip: alle Quelldateien, Hashliste, nie ueberschrieben ------------------------------------------------------------ p = S.tageszip(lauf, scratch, os.path.join(ziel, "livebaum"), alt, platz, "2026-11-29") assert p and os.path.isfile(p) and os.path.isfile(p[:-4] + ".sha256") with zipfile.ZipFile(p) as z: namen = z.namelist() summen = z.read("SHA256SUMS.txt").decode() assert "haende.jsonl" in namen and "scratch/laeufer.txt" in namen and "zaehler.json" in namen assert "haende.jsonl" in summen and "FEHLER" not in summen assert S.tageszip(lauf, scratch, os.path.join(ziel, "livebaum"), alt, platz, "2026-11-29") is None # schon da # --- Ziel im Repo wird verweigert; Dienst ohne PID-Doppel -------------------------------------------------------------- rb = os.path.join(wurzel, "repo", ".claude", "worktrees", "x") assert S.im_repo(os.path.join(wurzel, "repo", "archiv"), rb) and S.im_repo(os.path.join(rb, "a"), rb) assert not S.im_repo(ziel, rb) with open(os.path.join(ziel, "sicherung.pid"), "w") as f: f.write(str(os.getpid())) assert S._schon_da(os.path.join(ziel, "sicherung.pid")) is False # die eigene PID zaehlt nicht assert S.anstossen(starten=lambda *a, **k: (_ for _ in ()).throw(AssertionError("kein Start in der Spec")), ziel=ziel) is None # Startfehler wirft nie # wach_halten: hoechstens alle 600 s ein Blick (die Laeuferschleife ruft es jede Runde) gerufen = [] S.anstossen = lambda **kw: gerufen.append(1) S._WACH["letzt"] = None S.wach_halten(jetzt=1000.0); S.wach_halten(jetzt=1300.0); S.wach_halten(jetzt=1601.0) assert len(gerufen) == 2, gerufen print("sicherung_spec: ok")