sergio/takana
> Una distribución Linux construida con un laboratorio funcional y hermético en el > sótano, y una terminal mutable, clásica y anárquica en el piso de arriba — diseñada > desde el suelo para que una IA programadora entienda, modifique y co…
takana etapa 5c: comentarios de scripts, MOTD, y un BUG que introdujo la etapa 4
1#!/usr/bin/env python3
2# drive-rebuild.py — Driver NO-interactivo del rebuild in-rootfs (auto-alojamiento, SDD 11 §7;
3# runbook docs/runbooks/stage1-vm-boot.md §8c).
4#
5# Bootea el builder en QEMU, espera la shell de arje-zero (PID 1), manda `rebuild-stage1` y captura
6# todo hasta el veredicto (✓ REPRODUCIBLE / ✗ DIVERGENTE), el RC o el timeout. Imprime un resumen y
7# sale con 0 si REPRODUCIBLE, 1 si DIVERGENTE/otro.
8#
9# Variables de entorno (todas opcionales):
10# BUILDER_CPIO initramfs del builder (default work/builder.cpio.gz)
11# DISK imagen de disco PARTICIONADA (GPT) a bootear como ROOT real (Etapa B3). Si está
12# seteada, se ignora el initramfs: QEMU monta la imagen como disco virtio y el kernel
13# arranca con `root=/dev/vda1 rw rdinit=/sbin/init` — sin initramfs ni switch_root (/ ya
14# es un mount ext4 real, pivotable). La partición 1 es /, y el wrapper /sbin/init monta
15# las particiones dedicadas /store (vda2) y /var/lib/hammer (vda3) antes del init real.
16# La arma scripts/disk-image.sh. Requiere kernel con VIRTIO_BLK+EXT4 (recipes/linux.toml).
17# KERNEL bzImage/vmlinuz a bootear (default /boot/vmlinuz-linux)
18# MEM RAM de la VM en MiB (default 6144)
19# CPU modelo de CPU TCG (default Broadwell; AVX2 sin KVM)
20# KVM 1 ⇒ -enable-kvm -cpu host si hay /dev/kvm (mucho más rápido; recomendado)
21# DEADLINE techo en segundos (default 14400 = 4h)
22# LOG fichero de captura (default work/rebuild-run.log)
23# NET 1 ⇒ NIC e1000 user-mode para el vendoring Rust (default 1)
24#
25# El rebuild Rust (hammerd/arje-zero) hace `cargo vendor` desde crates.io ⇒ necesita red: por eso la
26# NIC e1000 (qemu user-mode 10.0.2.0/24). Sin red, sólo sellan los componentes C.
27import os, pty, select, subprocess, sys, time, re
28
29ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
30
31
32def envpath(name, default):
33 v = os.environ.get(name, default)
34 return v if os.path.isabs(v) else os.path.join(ROOT, v)
35
36
37CPIO = envpath("BUILDER_CPIO", "work/builder.cpio.gz")
38DISK = os.environ.get("DISK", "") # Etapa B: si está, booteamos de disco real en vez de initramfs.
39if DISK and not os.path.isabs(DISK):
40 DISK = os.path.join(ROOT, DISK)
41KERNEL = os.environ.get("KERNEL", "/boot/vmlinuz-linux")
42LOG = envpath("LOG", "work/rebuild-run.log")
43MEM = os.environ.get("MEM", "6144")
44CPU = os.environ.get("CPU", "Broadwell")
45DEADLINE = int(os.environ.get("DEADLINE", "14400"))
46WANT_KVM = os.environ.get("KVM", "0") == "1"
47WANT_NET = os.environ.get("NET", "1") == "1"
48
49_needed = [(DISK, "imagen de disco")] if DISK else [(CPIO, "initramfs del builder")]
50for p, what in _needed + [(KERNEL, "kernel")]:
51 if not os.path.exists(p):
52 sys.exit(f"no existe {what}: {p}")
53
54accel = ["-cpu", CPU]
55if WANT_KVM and os.access("/dev/kvm", os.W_OK):
56 accel = ["-enable-kvm", "-cpu", "host"]
57 print("==> KVM activo (-cpu host)")
58else:
59 print(f"==> TCG (sin KVM); -cpu {CPU}. Lento — el rebuild Rust puede tardar.")
60
61net = ["-netdev", "user,id=n0", "-device", "e1000,netdev=n0"] if WANT_NET else []
62
63# APPEND override: por defecto consola serie + initramfs. Útil para experimentar con params del kernel
64# (p.ej. el frente kernel-from-source: el bzImage takana bootea pero bwrap falla en pivot_root porque /
65# es el rootfs absoluto del namespace; `rootfstype=tmpfs` NO lo arregla — la causa es que / no tiene
66# mount padre, no el tipo de fs). Override con APPEND="…".
67# Boot de disco (Etapa B3) vs initramfs. En disco / ya es un mount ext4 real ⇒ rdinit=/sbin/init directo,
68# sin el wrapper switch_root del path initramfs. La GPT tiene 3 particiones: vda1=/ , vda2=/store ,
69# vda3=/var/lib/hammer; el kernel monta vda1 y el wrapper /sbin/init monta las otras dos.
70if DISK:
71 APPEND = os.environ.get("APPEND", "console=ttyS0 root=/dev/vda1 rw rdinit=/sbin/init")
72 media = ["-drive", f"file={DISK},if=virtio,format=raw", "-append", APPEND]
73else:
74 APPEND = os.environ.get("APPEND", "console=ttyS0 rdinit=/sbin/init")
75 media = ["-initrd", CPIO, "-append", APPEND]
76QEMU = (["qemu-system-x86_64", "-m", MEM, "-no-reboot", "-nographic"] + accel + net +
77 ["-kernel", KERNEL] + media)
78
79print(f"==> kernel : {KERNEL}")
80print(f"==> {'disco ' if DISK else 'initramfs '}: {DISK or CPIO}")
81print(f"==> mem : {MEM} MiB deadline: {DEADLINE}s net: {'sí' if WANT_NET else 'no'}")
82print(f"==> log : {LOG}")
83
84ansi = re.compile(rb'\x1b\[[0-9;?]*[a-zA-Z]')
85strip = lambda b: ansi.sub(b'', b)
86
87master, slave = pty.openpty()
88p = subprocess.Popen(QEMU, stdin=slave, stdout=slave, stderr=slave, close_fds=True)
89os.close(slave)
90log = open(LOG, "wb")
91buf = b""
92sent = False
93start = time.time()
94send = lambda s: os.write(master, s.encode())
95
96while True:
97 if time.time() - start > DEADLINE:
98 log.write(b"\n[DRIVER] DEADLINE\n")
99 break
100 r, _, _ = select.select([master], [], [], 10)
101 if r:
102 try:
103 data = os.read(master, 8192)
104 except OSError:
105 break
106 if not data:
107 break
108 log.write(data)
109 log.flush()
110 buf = strip(buf + data)[-20000:]
111 # Boot listo: arje-zero levantó hammerd (fanotify) o apareció la shell.
112 if not sent and (b"watcher fanotify activo" in buf or b"\n~ #" in buf or b"\r~ #" in buf):
113 time.sleep(3)
114 send("echo DRIVER_BEGIN; rebuild-stage1; echo DRIVER_RC=$?\n")
115 sent = True
116 log.write(b"\n[DRIVER] enviado rebuild-stage1\n")
117 log.flush()
118 # OJO: el comando tecleado ECHOA "DRIVER_RC=$?"; el marcador real es la SALIDA
119 # "DRIVER_RC=<digito>". Matchear sólo eso (o el veredicto) evita salir antes de tiempo.
120 if sent and (re.search(rb'DRIVER_RC=[0-9]', buf) or b"REPRODUCIBLE" in buf or b"DIVERGENTE" in buf):
121 time.sleep(2)
122 try:
123 log.write(os.read(master, 8192))
124 except Exception:
125 pass
126 log.write(b"\n[DRIVER] FIN (marcador)\n")
127 break
128 else:
129 if p.poll() is not None:
130 log.write(b"\n[DRIVER] qemu salio\n")
131 break
132
133try:
134 p.terminate()
135 time.sleep(2)
136 p.kill()
137except Exception:
138 pass
139log.close()
140
141# Veredicto a partir de lo capturado.
142blob = strip(open(LOG, "rb").read())
143ok = (b"REPRODUCIBLE" in blob) and (b"DIVERGENTE" not in blob)
144print(f"\nDRIVER done sent={sent} elapsed={int(time.time() - start)}s")
145if ok:
146 print("RESULTADO: ✓ REPRODUCIBLE — auto-alojamiento bit a bit verificado")
147elif b"DIVERGENTE" in blob:
148 print("RESULTADO: ✗ DIVERGENTE — hay no-determinismo que cazar (SDD 09 §2)")
149else:
150 print("RESULTADO: ? incompleto (timeout/boot/OOM) — revisá el log")
151sys.exit(0 if ok else 1)