tawasuyu
⎇ a4fa42c781d76852355931d82a28e80230855af8 crates/ente-zero/src/main.rs Rust · 426 líneas · 15.8 KB Historia Quién tocó qué crudo

Audit→CAS, reload rules, time-decay y forma canónica del hash chain a4fa42c78 · Sergio ·

1//! Ente #0 — el primer Ente. PID 1 del fractal.
2//!
3//! Reglas no negociables:
4//!   1. NUNCA lógica de servicio aquí. Sólo: leer Semilla, cosechar zombis,
5//!      mediar capacidades, propagar eventos.
6//!   2. Single-threaded. Cualquier paralelismo se delega a Entes worker.
7//!      Un panic en un thread de PID 1 = kernel panic.
8//!   3. Errores de hijos son *eventos* en `graph_tx`, no `Result` propagado.
9//!
10//! Este archivo es sólo wireup. La lógica vive en:
11//!   - `seed`        : construcción/restauración de la Tarjeta Semilla
12//!   - `bus`         : listener Unix + auth via SO_PEERCRED
13//!   - `graph::*`    : estado del fractal (lifecycle, topology, shutdown,
14//!                     bus_mediator, devices, capabilities)
15//!   - `events`      : tipos de eventos del bucle primordial
16//!   - crates externos del workspace para CAS, soma, wasm, snapshot, kernel.
17
18mod brain_glue;
19mod bus;
20mod events;
21mod graph;
22mod seed;
23
24use anyhow::Context;
25use ente_brain::{BrainState, IntrospectServer};
26use ente_kernel::{become_child_subreaper, bootstrap_kernel_surface, spawn_sigchld_stream, spawn_uevent_stream};
27use events::{ExitStatus, GraphEvent, ShutdownReason};
28use graph::EnteGraph;
29use nix::errno::Errno;
30use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
31use nix::unistd::{getpid, Pid};
32use std::path::PathBuf;
33use std::time::Duration;
34use tokio::sync::mpsc;
35use tracing::{error, info, warn};
36
37struct CliArgs {
38    checkpoint: Option<PathBuf>,
39    restore: Option<PathBuf>,
40    rules: Option<PathBuf>,
41    rules_out: Option<PathBuf>,
42    audit_head: Option<PathBuf>,
43    metrics_addr: Option<String>,
44    brain_half_life: Option<f64>,
45}
46
47fn parse_args() -> CliArgs {
48    let mut args = std::env::args().skip(1);
49    let mut checkpoint = None;
50    let mut restore = None;
51    let mut rules = None;
52    let mut rules_out = None;
53    let mut audit_head = None;
54    let mut metrics_addr = None;
55    let mut brain_half_life = None;
56    while let Some(a) = args.next() {
57        match a.as_str() {
58            "--checkpoint" => checkpoint = args.next().map(PathBuf::from),
59            "--restore" => restore = args.next().map(PathBuf::from),
60            "--rules" => rules = args.next().map(PathBuf::from),
61            "--rules-out" => rules_out = args.next().map(PathBuf::from),
62            "--audit-head" => audit_head = args.next().map(PathBuf::from),
63            "--metrics-addr" => metrics_addr = args.next(),
64            "--brain-half-life" => brain_half_life = args.next().and_then(|s| s.parse().ok()),
65            other => warn!(arg = %other, "argumento desconocido, ignorado"),
66        }
67    }
68    CliArgs { checkpoint, restore, rules, rules_out, audit_head, metrics_addr, brain_half_life }
69}
70
71fn main() -> anyhow::Result<()> {
72    init_tracing();
73    let cli = parse_args();
74    let pid = getpid();
75    let dev_mode = pid != Pid::from_raw(1);
76
77    if dev_mode {
78        warn!(?pid, "ente-zero corriendo en DEV MODE (no PID 1) — kernel surface no se monta");
79    } else {
80        info!("ente-zero despierta como PID 1");
81        bootstrap_kernel_surface().context("bootstrap kernel surface")?;
82        become_child_subreaper().context("PR_SET_CHILD_SUBREAPER")?;
83    }
84
85    let card = seed::load(dev_mode, cli.restore.as_deref())?;
86
87    // current_thread runtime: ver doctrina al inicio del módulo.
88    let rt = tokio::runtime::Builder::new_current_thread()
89        .enable_io()
90        .enable_time()
91        .build()?;
92
93    rt.block_on(primordial_loop(
94        card, dev_mode,
95        cli.checkpoint, cli.rules, cli.rules_out,
96        cli.audit_head, cli.metrics_addr, cli.brain_half_life,
97    ))
98}
99
100async fn primordial_loop(
101    seed_card: ente_card::EntityCard,
102    dev_mode: bool,
103    checkpoint_path: Option<PathBuf>,
104    rules_path: Option<PathBuf>,
105    rules_out: Option<PathBuf>,
106    audit_head: Option<PathBuf>,
107    metrics_addr: Option<String>,
108    brain_half_life: Option<f64>,
109) -> anyhow::Result<()> {
110    info!(seed_id = %seed_card.id, label = %seed_card.label, "Ente #0 entra al bucle primordial");
111
112    let (graph_tx, mut graph_rx) = mpsc::channel::<GraphEvent>(64);
113    let mut sigchld = spawn_sigchld_stream()?;
114    // Uevents puede fallar en dev (sin CAP_NET_ADMIN). Degradamos a un
115    // canal nunca-listo en lugar de abortar el bucle primordial.
116    let mut uevents = match spawn_uevent_stream() {
117        Ok(rx) => rx,
118        Err(e) => {
119            warn!(?e, "uevents deshabilitados (probablemente falta CAP_NET_ADMIN)");
120            let (_keep_tx, rx) = mpsc::channel::<ente_kernel::UEvent>(1);
121            std::mem::forget(_keep_tx);
122            rx
123        }
124    };
125
126    // Bus interno: listener antes de spawn de hijos para que su Announce
127    // tenga adónde llegar. Su path se inyecta en ENTE_BUS_SOCK por soma.
128    let bus_sock = bus::default_socket_path();
129    let bus_path = bus::spawn_bus(bus_sock, graph_tx.clone())?;
130    ente_soma::set_bus_sock(bus_path.to_string_lossy().into_owned());
131
132    let mut graph = EnteGraph::new(seed_card);
133    graph.instantiate_seed_dependencies(&graph_tx).await?;
134
135    // Cerebro: BrainState compartido + servidor de introspección.
136    // Window de 1024 eventos — suficiente para correlaciones interesantes
137    // sin gastar memoria de PID 1. En dev bajamos el umbral de cristalización
138    // para que el demo (pocos eventos) produzca cristales observables.
139    let mut brain = if dev_mode {
140        // Umbrales relajados para que el demo (pocos eventos) produzca
141        // cristales observables. Con P(b|a) normalizada a [0,1], los
142        // valores típicos en muestras pequeñas son 0.2-0.5.
143        BrainState::with_params(1024, ente_brain::CrystallizationParams {
144            min_support: 2,
145            min_conditional_prob: 0.3,
146            min_pmi: 1.0,
147        })
148    } else {
149        BrainState::new(1024)
150    };
151    if let Some(out_path) = rules_out {
152        brain = brain.with_rules_out(out_path);
153    }
154    if let Some(hl) = brain_half_life {
155        let mut obs = brain.observer.write().await;
156        // Reemplazar con un observer nuevo que tenga half-life. Estado
157        // anterior (vacío en este punto) descartado.
158        *obs = ente_brain::Observer::new(1024).with_half_life(hl);
159        info!(hl_secs = hl, "observer con time-decay activo");
160    }
161    // Si --audit-head, configuramos el head pointer y arrancamos auto-flush.
162    if let Some(head_path) = audit_head {
163        // Re-creamos el AuditLog con head pointer.
164        let new_audit = ente_brain::audit::AuditLog::new()
165            .with_head_pointer(head_path);
166        *brain.audit.write().await = new_audit;
167        spawn_audit_auto_flush(brain.clone());
168    }
169
170    // Carga inicial de reglas vía KCL o JSON, si --rules path proporcionado.
171    if let Some(path) = &rules_path {
172        match ente_brain::load_rules_file(path) {
173            Ok(rules) => {
174                let mut engine = brain.engine.write().await;
175                for r in rules {
176                    engine.insert(r);
177                }
178                info!(count = engine.len(), path = %path.display(), "reglas cargadas");
179            }
180            Err(e) => warn!(?e, path = %path.display(), "carga de reglas falló"),
181        }
182    }
183
184    // Endpoint Prometheus opcional. En dev por defecto en 127.0.0.1:9911 si
185    // el flag no se pasó.
186    let metrics_addr = metrics_addr.or_else(|| {
187        if dev_mode { Some("127.0.0.1:9911".to_string()) } else { None }
188    });
189    if let Some(addr_s) = metrics_addr {
190        match addr_s.parse::<std::net::SocketAddr>() {
191            Ok(addr) => {
192                let s = brain.clone();
193                tokio::spawn(async move {
194                    if let Err(e) = ente_brain::serve_metrics(s, addr).await {
195                        warn!(?e, "metrics server cayó");
196                    }
197                });
198            }
199            Err(e) => warn!(?e, addr = %addr_s, "metrics-addr inválido"),
200        }
201    }
202    spawn_brain_introspect(brain.clone());
203    let brain_sink = brain_glue::GraphSink {
204        graph_tx: graph_tx.clone(),
205        // Spawns auto-disparados desde reglas usan la identidad de la Semilla
206        // (único Ente con Capability::Spawn por construcción).
207        requester: graph.seed_id(),
208    };
209
210    // Demo automático del forwarding (sólo dev, sólo si el binario existe).
211    if dev_mode && std::path::Path::new("target/debug/ente-echo").exists() {
212        spawn_echo_smoke_test(bus_path.clone());
213    }
214
215    // En dev mode no tenemos hijos por defecto y el bucle se quedaría inerte.
216    let dev_exit = if dev_mode {
217        Some(tokio::time::sleep(Duration::from_secs(4)))
218    } else {
219        None
220    };
221    tokio::pin!(dev_exit);
222
223    loop {
224        tokio::select! {
225            biased;
226
227            Some(_) = sigchld.recv() => {
228                reap_until_empty(&mut graph, &graph_tx).await;
229            }
230
231            Some(uevt) = uevents.recv() => {
232                graph.on_uevent(uevt, &graph_tx).await;
233            }
234
235            Some(evt) = graph_rx.recv() => {
236                // Cerebro observa antes que el grafo mute. Snapshot del
237                // SubjectInfo se hace contra el estado pre-mutación.
238                feed_brain(&brain, &brain_sink, &graph, &evt).await;
239                if dispatch_graph_event(&mut graph, evt, &graph_tx, &checkpoint_path).await {
240                    return Ok(());
241                }
242            }
243
244            _ = async { dev_exit.as_mut().as_pin_mut().unwrap().await }, if dev_mode => {
245                info!("dev mode: timer expirado, cerrando bucle primordial");
246                let _ = graph_tx.send(GraphEvent::Shutdown {
247                    reason: ShutdownReason::SeedRequested,
248                }).await;
249            }
250        }
251    }
252}
253
254/// Devuelve `true` si el bucle primordial debe terminar.
255async fn dispatch_graph_event(
256    graph: &mut EnteGraph,
257    evt: GraphEvent,
258    tx: &mpsc::Sender<GraphEvent>,
259    checkpoint: &Option<PathBuf>,
260) -> bool {
261    match evt {
262        GraphEvent::EnteDied { id, status } => {
263            graph.on_death(id, status, tx).await;
264        }
265        GraphEvent::CapabilityRequested { from, cap, reply } => {
266            graph.mediate_capability(from, cap, reply).await;
267        }
268        GraphEvent::SpawnRequest { card, requester } => {
269            if let Err(e) = graph.authorize_and_spawn(card, requester).await {
270                warn!(?e, "spawn request error");
271            }
272        }
273        GraphEvent::BusRequest { peer, from, request, outbound, reply } => {
274            graph.on_bus_request(peer, from, request, outbound, reply).await;
275        }
276        GraphEvent::BusResponse { seq, response } => {
277            graph.on_bus_response(seq, response).await;
278        }
279        GraphEvent::BusConnClosed { ente_id } => {
280            graph.on_bus_conn_closed(ente_id).await;
281        }
282        GraphEvent::Shutdown { reason } => {
283            warn!(?reason, "shutdown del fractal");
284            if let Some(path) = checkpoint.as_ref() {
285                let snap = graph.snapshot();
286                match snap.write(path) {
287                    Ok(()) => info!(path = %path.display(), entes = snap.entes.len(), "snapshot persistido"),
288                    Err(e) => warn!(?e, "snapshot write falló"),
289                }
290            }
291            graph.cascade_shutdown().await;
292            return true;
293        }
294    }
295    false
296}
297
298async fn reap_until_empty(graph: &mut EnteGraph, tx: &mpsc::Sender<GraphEvent>) {
299    loop {
300        match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
301            Ok(WaitStatus::StillAlive) => return,
302            Ok(WaitStatus::Exited(pid, code)) => {
303                emit_death(graph, tx, pid, ExitStatus::Exit(code)).await;
304            }
305            Ok(WaitStatus::Signaled(pid, sig, _core)) => {
306                emit_death(graph, tx, pid, ExitStatus::Killed(sig)).await;
307            }
308            Ok(_) => continue, // Stopped/Continued — irrelevantes
309            Err(Errno::ECHILD) => return,
310            Err(e) => {
311                error!(?e, "waitpid fallo no recuperable en bucle de reaping");
312                return;
313            }
314        }
315    }
316}
317
318async fn emit_death(
319    graph: &EnteGraph,
320    tx: &mpsc::Sender<GraphEvent>,
321    pid: Pid,
322    status: ExitStatus,
323) {
324    let id = match graph.lookup_pid(pid) {
325        Some(id) => id,
326        None => {
327            // Proceso adoptado (subreaper): no está en nuestro grafo.
328            info!(?pid, ?status, "huérfano cosechado (no en grafo)");
329            return;
330        }
331    };
332    let _ = tx.send(GraphEvent::EnteDied { id, status }).await;
333}
334
335fn spawn_echo_smoke_test(bus_path: PathBuf) {
336    tokio::spawn(async move {
337        tokio::time::sleep(Duration::from_millis(300)).await;
338        match ente_bus::BusClient::connect(&bus_path).await {
339            Ok(mut client) => {
340                let req = ente_bus::BusRequest::Invoke {
341                    cap: ente_echo::echo_capability(),
342                    blob: b"hola fractal forwardeado".to_vec(),
343                };
344                match client.call(req).await {
345                    Ok(ente_bus::BusResponse::Invoked { result }) => {
346                        info!(echo = %String::from_utf8_lossy(&result), "Invoke ECHO round-trip OK");
347                    }
348                    Ok(other) => warn!(?other, "Invoke ECHO respuesta inesperada"),
349                    Err(e) => warn!(?e, "Invoke ECHO falló"),
350                }
351            }
352            Err(e) => warn!(?e, "no se pudo conectar al bus para test"),
353        }
354    });
355}
356
357fn init_tracing() {
358    use tracing_subscriber::{fmt, EnvFilter};
359    let filter = EnvFilter::try_from_default_env()
360        .unwrap_or_else(|_| EnvFilter::new("ente_zero=debug,info"));
361    fmt().with_env_filter(filter).with_target(true).init();
362}
363
364fn brain_introspect_path() -> PathBuf {
365    if let Ok(p) = std::env::var("ENTE_BRAIN_SOCK") {
366        return p.into();
367    }
368    let runtime = std::env::var("XDG_RUNTIME_DIR")
369        .unwrap_or_else(|_| std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()));
370    format!("{runtime}/ente-brain.sock").into()
371}
372
373/// Auto-flush del audit log a CAS cada 10 segundos. Ejecuta best-effort:
374/// si el flush falla lo logeamos pero no abortamos. La integridad del log
375/// queda garantizada por su hash chain — re-flushar es idempotente.
376fn spawn_audit_auto_flush(state: BrainState) {
377    tokio::spawn(async move {
378        let mut tick = tokio::time::interval(std::time::Duration::from_secs(10));
379        tick.tick().await; // descartar primer tick inmediato
380        loop {
381            tick.tick().await;
382            let mut audit = state.audit.write().await;
383            match audit.flush_to_cas() {
384                Ok(0) => {} // nada nuevo
385                Ok(n) => info!(written = n, total = audit.flushed_count(), "audit auto-flush"),
386                Err(e) => warn!(?e, "audit auto-flush falló"),
387            }
388        }
389    });
390}
391
392fn spawn_brain_introspect(state: BrainState) {
393    let path = brain_introspect_path();
394    tokio::spawn(async move {
395        let server = IntrospectServer::new(state);
396        if let Err(e) = server.serve(&path).await {
397            warn!(?e, "introspect server cayó");
398        }
399    });
400}
401
402/// Registra el evento en el observer y dispatcha cualquier regla matched.
403/// Para reglas Sequence: pasamos los últimos N eventos del observer como
404/// history al engine.
405async fn feed_brain(
406    brain: &BrainState,
407    sink: &brain_glue::GraphSink,
408    graph: &EnteGraph,
409    evt: &GraphEvent,
410) {
411    let Some((kind, subj)) = brain_glue::graph_event_to_brain(evt, graph) else { return };
412    let history: Vec<ente_brain::TimedEvent> = {
413        let mut obs = brain.observer.write().await;
414        obs.record(kind.clone());
415        // Snapshot de los últimos 16 eventos — suficiente para cualquier
416        // Sequence pattern razonable. Clone hace una sola alocación.
417        obs.recent(16).cloned().collect()
418    };
419    let rules = {
420        let engine = brain.engine.read().await;
421        engine.dispatch(&kind, &subj, &history)
422    };
423    if !rules.is_empty() {
424        ente_brain::dispatch_actions(&rules, sink).await;
425    }
426}