chore: monorepo inicial con arje + minga + yahweh absorbidos
Workspace en 4 ejes (core/modules/apps/shared):
- core/: 24 crates de arje (Init systemd-compatible: ente-card, ente-zero,
ente-kernel, ente-bus, ente-cas, ente-soma, ente-wasm, ente-snapshot,
ente-brain, ente-echo, ente-policy-provider, + 12 crates *-compat)
- modules/semantic_dht/: 5 crates de minga (minga-core con AST/CAS/MST,
minga-p2p con libp2p Kad, minga-store, minga-vfs, minga-cli)
- modules/ui_engine/: 11 crates de yahweh (libs/{core,theme,bus,providers},
widgets/{tree,splitter,tabs,tiled,container_core,text_input})
- apps/: 5 crates de yahweh (file_explorer, database_explorer, text_viewer,
image_viewer, yahweh-shell)
- shared_wit/protocol.wit: handshake/lifecycle inicial
Cargo.toml unificado: thiserror bumped a 2 (transparente para arje), tokio
"full", paths intra-workspace de yahweh redirigidos a su nueva ubicación.
cargo check --workspace: 0 errores, 17 warnings (dead code preexistente).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "ente-binfmt-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-binfmt-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,109 @@
|
||||
//! ente-binfmt-compat: registra handlers de binfmt_misc al boot.
|
||||
//!
|
||||
//! systemd-binfmt lee `/usr/lib/binfmt.d/*.conf` y `/etc/binfmt.d/*.conf` y
|
||||
//! escribe cada línea al kernel via `/proc/sys/fs/binfmt_misc/register`.
|
||||
//! Esto habilita ejecución transparente de binarios no-ELF (qemu-user,
|
||||
//! wine, etc).
|
||||
//!
|
||||
//! Formato de cada línea:
|
||||
//! :<name>:<type>:<offset>:<magic>:<mask>:<interpreter>:<flags>
|
||||
//!
|
||||
//! Líneas que empiezan con `#` o vacías se ignoran.
|
||||
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const REGISTER_PATH: &str = "/proc/sys/fs/binfmt_misc/register";
|
||||
const SEARCH_DIRS: &[&str] = &[
|
||||
"/usr/lib/binfmt.d",
|
||||
"/etc/binfmt.d",
|
||||
"/run/binfmt.d",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
init_tracing();
|
||||
info!("ente-binfmt-compat: registrando handlers binfmt_misc");
|
||||
|
||||
if !Path::new(REGISTER_PATH).exists() {
|
||||
warn!(path = REGISTER_PATH, "binfmt_misc no montado — skip");
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
let mut registered = 0;
|
||||
let mut errors = 0;
|
||||
let mut skipped = 0;
|
||||
|
||||
for dir in SEARCH_DIRS {
|
||||
if !Path::new(dir).exists() { continue; }
|
||||
let mut entries: Vec<_> = match fs::read_dir(dir) {
|
||||
Ok(rd) => rd.filter_map(|e| e.ok()).collect(),
|
||||
Err(_) => continue,
|
||||
};
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if path.extension().map(|e| e != "conf").unwrap_or(true) { continue; }
|
||||
let content = match fs::read_to_string(&path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => { warn!(?e, path = %path.display(), "read"); continue; }
|
||||
};
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') { continue; }
|
||||
match register(line) {
|
||||
Ok(name) => {
|
||||
info!(file = %path.display(), %name, "binfmt registrado");
|
||||
registered += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_already_exists() {
|
||||
skipped += 1;
|
||||
} else {
|
||||
warn!(?e, file = %path.display(), "registro falló");
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
info!(registered, skipped, errors, "binfmt aplicado");
|
||||
if errors > 0 { std::process::exit(1); }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RegError(std::io::Error);
|
||||
impl std::fmt::Display for RegError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
|
||||
}
|
||||
impl RegError {
|
||||
fn is_already_exists(&self) -> bool {
|
||||
// EEXIST = 17 en Linux.
|
||||
self.0.raw_os_error() == Some(17)
|
||||
}
|
||||
}
|
||||
|
||||
/// Escribe la línea al register file. Devuelve el `name` extraído del
|
||||
/// primer campo (entre `:` separators) si tuvo éxito.
|
||||
fn register(line: &str) -> Result<String, RegError> {
|
||||
// Sintaxis: :<name>:<type>:<offset>:<magic>:<mask>:<interpreter>:<flags>
|
||||
// Field 0 (después del ':' inicial) es el name.
|
||||
let name = line.split(':').nth(1)
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| "?".into());
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(REGISTER_PATH)
|
||||
.map_err(RegError)?;
|
||||
f.write_all(line.as_bytes()).map_err(RegError)?;
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_binfmt_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "ente-brain"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-cas = { path = "../ente-cas" }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
bincode = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
postcard = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[[example]]
|
||||
name = "brainctl"
|
||||
path = "examples/brainctl.rs"
|
||||
@@ -0,0 +1,234 @@
|
||||
//! brainctl: cliente CLI del introspect API.
|
||||
//!
|
||||
//! Uso:
|
||||
//! cargo run --example brainctl -p ente-brain -- list-rules
|
||||
//! cargo run --example brainctl -p ente-brain -- entropy
|
||||
//! cargo run --example brainctl -p ente-brain -- top 10
|
||||
//! cargo run --example brainctl -p ente-brain -- crystals
|
||||
//! cargo run --example brainctl -p ente-brain -- crystal-json 0
|
||||
//!
|
||||
//! Path del socket: $ENTE_BRAIN_SOCK o $XDG_RUNTIME_DIR/ente-brain.sock
|
||||
|
||||
use ente_brain::introspect::{call, IntrospectRequest, IntrospectResponse};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
fn socket_path() -> PathBuf {
|
||||
if let Ok(p) = std::env::var("ENTE_BRAIN_SOCK") {
|
||||
return p.into();
|
||||
}
|
||||
let runtime = std::env::var("XDG_RUNTIME_DIR")
|
||||
.unwrap_or_else(|_| std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()));
|
||||
format!("{runtime}/ente-brain.sock").into()
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("entropy");
|
||||
|
||||
// Comando especial: streaming. Mantiene la conn abierta y lee frames
|
||||
// hasta Ctrl-C o EOF del servidor.
|
||||
if cmd == "stream-audit" || cmd == "stream" {
|
||||
return run_stream_audit(socket_path()).await;
|
||||
}
|
||||
|
||||
let req = match cmd {
|
||||
"list-rules" | "rules" => IntrospectRequest::ListRules,
|
||||
"entropy" => IntrospectRequest::EntropySnapshot,
|
||||
"top" => {
|
||||
let n: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(10);
|
||||
IntrospectRequest::TopCorrelations { n }
|
||||
}
|
||||
"crystals" => IntrospectRequest::Crystals,
|
||||
"crystal-json" => {
|
||||
let i: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
IntrospectRequest::CrystalJson { index: i }
|
||||
}
|
||||
"promote" => {
|
||||
let i: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
IntrospectRequest::PromoteCrystal { index: i }
|
||||
}
|
||||
"remove" => {
|
||||
let id_s = args.get(2).ok_or_else(|| anyhow::anyhow!("se requiere <ulid>"))?;
|
||||
let id: ulid::Ulid = id_s.parse()?;
|
||||
IntrospectRequest::RemoveRule { id }
|
||||
}
|
||||
"audit" => {
|
||||
let limit: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(20);
|
||||
IntrospectRequest::ListAudit { limit }
|
||||
}
|
||||
"flush-audit" => IntrospectRequest::FlushAudit,
|
||||
"audit-verify" | "verify" => IntrospectRequest::VerifyAudit,
|
||||
"replay" => IntrospectRequest::ReplayAudit,
|
||||
"gc-cas" => IntrospectRequest::GcCas { extra_roots: Vec::new() },
|
||||
"patterns" => IntrospectRequest::PatternCrystals,
|
||||
"reload" => {
|
||||
let path = args.get(2).cloned();
|
||||
IntrospectRequest::ReloadRules { path }
|
||||
}
|
||||
other => {
|
||||
eprintln!("subcomando desconocido: {other}");
|
||||
eprintln!("válidos: list-rules | entropy | top <n> | crystals | crystal-json <i> | promote <i> | remove <ulid> | audit <limit> | flush-audit | reload [path]");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
|
||||
let path = socket_path();
|
||||
let resp = call(&path, req).await?;
|
||||
print_response(&resp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_response(r: &IntrospectResponse) {
|
||||
match r {
|
||||
IntrospectResponse::Rules(rs) => {
|
||||
println!("{} reglas vivas:", rs.len());
|
||||
for r in rs {
|
||||
println!(" {} prio={} kind={} actions={} wildcard={}",
|
||||
r.id, r.priority, r.event_kind_tag, r.action_count, r.scope_wildcard);
|
||||
}
|
||||
}
|
||||
IntrospectResponse::Rule(rule) => match rule {
|
||||
Some(r) => println!("{r:#?}"),
|
||||
None => println!("regla no encontrada"),
|
||||
},
|
||||
IntrospectResponse::Entropy { value_bits, sample_size, distinct_kinds, window_full } => {
|
||||
println!("Shannon entropy : {value_bits:.4} bits");
|
||||
println!("Sample size : {sample_size}");
|
||||
println!("Distinct kinds : {distinct_kinds}");
|
||||
println!("Window full : {window_full}");
|
||||
}
|
||||
IntrospectResponse::Correlations(entries) => {
|
||||
println!("{} pares (top, ordenado por co-ocurrencia):", entries.len());
|
||||
for e in entries {
|
||||
println!(" n={:>4} P(b|a)={:.3} PMI={:>6.3}b {} → {}",
|
||||
e.joint_count, e.conditional_prob, e.pmi_bits, e.a, e.b);
|
||||
}
|
||||
}
|
||||
IntrospectResponse::Crystals(cs) => {
|
||||
println!("{} cristales detectados:", cs.len());
|
||||
for (i, c) in cs.iter().enumerate() {
|
||||
println!(" [{i}] {:?} → {:?} P={:.3} PMI={:.3}b n={}",
|
||||
c.antecedent, c.consequent, c.conditional_prob, c.pmi, c.support);
|
||||
}
|
||||
}
|
||||
IntrospectResponse::Json(s) => println!("{s}"),
|
||||
IntrospectResponse::Promoted { rule_id, rule_json } => {
|
||||
println!("regla creada: {rule_id}");
|
||||
println!("--- JSON para auditoría / persistencia ---");
|
||||
println!("{rule_json}");
|
||||
}
|
||||
IntrospectResponse::Removed(was_present) => {
|
||||
if *was_present { println!("regla eliminada"); }
|
||||
else { println!("regla no encontrada"); }
|
||||
}
|
||||
IntrospectResponse::AuditEntries(entries) => {
|
||||
println!("{} entries de audit log:", entries.len());
|
||||
for e in entries {
|
||||
let prev = e.prev_sha.map(hex_short).unwrap_or_else(|| "—".into());
|
||||
let sha = hex_short(e.sha);
|
||||
println!(" seq={:>4} t={} prev={} sha={} {:?}",
|
||||
e.seq, e.timestamp_ms, prev, sha, e.action);
|
||||
}
|
||||
}
|
||||
IntrospectResponse::Flushed { written, head_sha, total_flushed } => {
|
||||
println!("flushed: {written} entries esta pasada, total acumulado: {total_flushed}");
|
||||
if let Some(sha) = head_sha {
|
||||
println!("head sha: {}", hex_long(*sha));
|
||||
}
|
||||
}
|
||||
IntrospectResponse::Reloaded { count } => {
|
||||
println!("reload OK: {count} reglas activas tras reload");
|
||||
}
|
||||
IntrospectResponse::Replayed(rep) => {
|
||||
if let Some(e) = &rep.error {
|
||||
println!("✗ replay falló: {e}");
|
||||
} else {
|
||||
println!("✓ replay completo — {} actions aplicadas, {} reglas finales",
|
||||
rep.applied, rep.final_rule_count);
|
||||
}
|
||||
}
|
||||
IntrospectResponse::AuditVerified(rep) => {
|
||||
if let Some(seq) = rep.broken_at_seq {
|
||||
println!("✗ verificación FALLÓ tras seq={seq}");
|
||||
if let Some(e) = &rep.error { println!(" motivo: {e}"); }
|
||||
println!(" entries verificadas: {}", rep.verified);
|
||||
} else {
|
||||
println!("✓ chain verificada — {} entries íntegras", rep.verified);
|
||||
if let Some(g) = rep.genesis_sha { println!(" genesis: {}", hex_long(g)); }
|
||||
}
|
||||
}
|
||||
IntrospectResponse::Patterns(ps) => {
|
||||
println!("{} cristales pattern detectados:", ps.len());
|
||||
for p in ps {
|
||||
match p {
|
||||
ente_brain::crystallize::PatternCrystal::Burst { kind, count, frequency_per_sec } => {
|
||||
println!(" burst: {kind:?} count={count} freq={frequency_per_sec:.2} Hz");
|
||||
}
|
||||
ente_brain::crystallize::PatternCrystal::Silence { kind, last_count, since_secs } => {
|
||||
println!(" silence: {kind:?} last_count={last_count} ausente={since_secs:.1}s");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
IntrospectResponse::GcResult { deleted, freed_bytes } => {
|
||||
println!("CAS gc: {deleted} blobs eliminados, {freed_bytes} bytes liberados");
|
||||
}
|
||||
IntrospectResponse::AuditStreamFrame(_) => {
|
||||
// En modo request/response no debería llegar; solo aparece en
|
||||
// run_stream_audit. Si llega aquí es un bug del servidor.
|
||||
eprintln!("frame de stream recibido fuera de stream-audit (bug)");
|
||||
}
|
||||
IntrospectResponse::Error(e) => eprintln!("error: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_short(sha: [u8; 32]) -> String {
|
||||
sha[..4].iter().map(|b| format!("{:02x}", b)).collect::<String>() + ".."
|
||||
}
|
||||
|
||||
fn hex_long(sha: [u8; 32]) -> String {
|
||||
sha.iter().map(|b| format!("{:02x}", b)).collect()
|
||||
}
|
||||
|
||||
async fn run_stream_audit(path: PathBuf) -> anyhow::Result<()> {
|
||||
let mut stream = UnixStream::connect(&path).await?;
|
||||
let req = IntrospectRequest::StreamAudit;
|
||||
let buf = bincode::serialize(&req)?;
|
||||
stream.write_u32(buf.len() as u32).await?;
|
||||
stream.write_all(&buf).await?;
|
||||
eprintln!("audit stream conectado a {} — Ctrl-C para salir", path.display());
|
||||
|
||||
loop {
|
||||
let mut len_buf = [0u8; 4];
|
||||
if stream.read_exact(&mut len_buf).await.is_err() {
|
||||
eprintln!("\nstream cerrado por el servidor");
|
||||
return Ok(());
|
||||
}
|
||||
let len = u32::from_be_bytes(len_buf) as usize;
|
||||
if len > 4 * 1024 * 1024 { anyhow::bail!("frame oversize"); }
|
||||
let mut buf = vec![0u8; len];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let resp: IntrospectResponse = bincode::deserialize(&buf)?;
|
||||
match resp {
|
||||
IntrospectResponse::AuditStreamFrame(entry) => {
|
||||
let prev = entry.prev_sha
|
||||
.map(|s| s[..4].iter().map(|b| format!("{:02x}", b)).collect::<String>() + "..")
|
||||
.unwrap_or_else(|| "—".into());
|
||||
let sha = entry.sha[..4].iter().map(|b| format!("{:02x}", b))
|
||||
.collect::<String>() + "..";
|
||||
println!("[stream] seq={} prev={} sha={} {:?}",
|
||||
entry.seq, prev, sha, entry.action);
|
||||
}
|
||||
other => {
|
||||
eprintln!("frame no esperado en stream: {other:?}");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn _suppress(_: &Path) {} // mantener Path import si compilador se queja
|
||||
@@ -0,0 +1,167 @@
|
||||
# ============================================================================
|
||||
# rule.k — REFERENCE ONLY. NOT LOADED.
|
||||
#
|
||||
# La gramática autoritativa de Rule vive en Rust:
|
||||
# crates/ente-brain/src/rules.rs
|
||||
# El loader (crates/ente-brain/src/loader.rs) sólo acepta JSON / JSONL.
|
||||
#
|
||||
# Conservado como notas de diseño humano-legibles del shape Rule:
|
||||
# Triplet [Sujeto + Evento + Acción(Objeto)]. Cada regla es una sinapsis:
|
||||
# cuando ocurre `when`, el motor ejecuta `then` para los Entes que cumplen
|
||||
# `scope`. El motor las indexa por discriminante de EventKind para lookup
|
||||
# en O(1). Las reglas son inmutables tras carga (Arc<Rule>).
|
||||
#
|
||||
# Si cambias el shape en Rust, sincroniza este archivo a mano (o
|
||||
# reemplázalo por JSON Schema generado vía `schemars`).
|
||||
# ============================================================================
|
||||
|
||||
schema Rule:
|
||||
"""Una sinapsis del fractal. Determinista, sin estado entre disparos."""
|
||||
id: str # Ulid 26 chars
|
||||
priority: int = 5 # 0..255, mayor = se ejecuta primero
|
||||
when: EventPattern
|
||||
then: [Action]
|
||||
scope: Scope = Scope {} # qué Entes son sujetos válidos
|
||||
|
||||
check:
|
||||
len(id) == 26, "id debe ser Ulid"
|
||||
priority >= 0 and priority <= 255, "priority fuera de rango"
|
||||
len(then) > 0, "regla sin acciones"
|
||||
|
||||
|
||||
# ---------- Subject: alcance del sujeto ----------
|
||||
|
||||
schema Scope:
|
||||
"""Match del sujeto. None en todos los campos = match cualquier Ente."""
|
||||
subject_id?: str # Ulid exacto
|
||||
subject_label?: str # label exacto
|
||||
subject_has_cap?: Capability # Ente que declara esta capacidad
|
||||
|
||||
check:
|
||||
subject_id is None or len(subject_id) == 26, "subject_id no es Ulid"
|
||||
|
||||
|
||||
# ---------- Event: qué dispara la regla ----------
|
||||
|
||||
# EventPattern es tagged union recursivo.
|
||||
#
|
||||
# Atómicos:
|
||||
# Single — match un evento por kind
|
||||
# Sequence — N eventos consecutivos dentro de within_ms
|
||||
#
|
||||
# Compuestos (recursivos):
|
||||
# Either — OR sobre sub-patterns
|
||||
# All — AND sobre sub-patterns (mismo event/history)
|
||||
schema EventPattern:
|
||||
type: "Single" | "Sequence" | "Either" | "All"
|
||||
kind?: EventKind # Single
|
||||
kinds?: [EventKind] # Sequence
|
||||
within_ms?: int = 0
|
||||
patterns?: [EventPattern] # Either / All (recursivo)
|
||||
|
||||
check:
|
||||
type != "Single" or kind is not None, "Single requiere kind"
|
||||
type != "Sequence" or (kinds is not None and len(kinds) > 0), \
|
||||
"Sequence requiere kinds no vacío"
|
||||
type != "Either" or (patterns is not None and len(patterns) > 0), \
|
||||
"Either requiere patterns no vacío"
|
||||
type != "All" or (patterns is not None and len(patterns) > 0), \
|
||||
"All requiere patterns no vacío"
|
||||
within_ms is None or within_ms >= 0, "within_ms negativo"
|
||||
|
||||
|
||||
# EventKind con tag interno + payload opcional según tag.
|
||||
schema EventKind:
|
||||
tag: "EnteSpawned" | "EnteDied" | "BusAnnounce" | "BusInvoke" | "BusInvokeOf" | "DeviceAdded" | "DeviceRemoved" | "Custom"
|
||||
cap?: Capability # para BusInvokeOf
|
||||
custom?: str # para Custom
|
||||
|
||||
check:
|
||||
tag != "BusInvokeOf" or cap is not None, "BusInvokeOf requiere cap"
|
||||
tag != "Custom" or custom is not None, "Custom requiere custom string"
|
||||
|
||||
|
||||
# ---------- Action: qué hacer ----------
|
||||
|
||||
schema Action:
|
||||
"""Una acción ejecutable por el motor. Tagged union con kind."""
|
||||
kind: "Log" | "Notify" | "Spawn" | "Invoke" | "Inhibit"
|
||||
# Log
|
||||
level?: "trace" | "debug" | "info" | "warn" | "error"
|
||||
message?: str
|
||||
# Notify
|
||||
target_id?: str # Ulid
|
||||
# Spawn
|
||||
card_blob?: str # base64-encoded EntityCard JSON
|
||||
# Invoke
|
||||
target_cap?: Capability
|
||||
blob_b64?: str
|
||||
# Inhibit
|
||||
reason?: str
|
||||
|
||||
check:
|
||||
kind != "Log" or message is not None, "Log requiere message"
|
||||
kind != "Notify" or (target_id is not None and message is not None), \
|
||||
"Notify requiere target_id + message"
|
||||
kind != "Spawn" or card_blob is not None, "Spawn requiere card_blob"
|
||||
kind != "Invoke" or target_cap is not None, "Invoke requiere target_cap"
|
||||
kind != "Inhibit" or reason is not None, "Inhibit requiere reason"
|
||||
|
||||
|
||||
# ---------- Capability: re-export desde card.k para evitar inclusión circular ----------
|
||||
|
||||
# En uso real: `import ..ente_card.schema.card` y referencia Capability.
|
||||
# Aquí declaramos una versión alineada para auto-contención del esquema.
|
||||
schema Capability:
|
||||
kind: "FilesystemRoot" | "KernelNetlink" | "Endpoint" | "LegacyLogind" | "Device" | "Spawn" | "Journal"
|
||||
netlink_family?: "Uevent" | "Route" | "Generic" | "Audit"
|
||||
endpoint_interface?: str
|
||||
endpoint_version?: int
|
||||
device_class?: "Block" | "Tty" | "Input" | "Drm" | "Net" | "Hidraw"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Ejemplo de regla cristalizada (auto-generada por el observador)
|
||||
# ============================================================================
|
||||
|
||||
example_rule = Rule {
|
||||
id = "01KQQ100000000000000000000"
|
||||
priority = 5
|
||||
when = EventPattern {
|
||||
type = "Single"
|
||||
kind = EventKind {tag = "EnteSpawned"}
|
||||
}
|
||||
scope = Scope {
|
||||
subject_label = "demo-echo"
|
||||
}
|
||||
then = [
|
||||
Action {
|
||||
kind = "Log"
|
||||
level = "info"
|
||||
message = "demo-echo encarnado, observando para crystallization"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# Ejemplo de regla compuesta: cuando un Ente se anuncia y luego es invocado
|
||||
# en menos de 500ms, log estructurado para auditoría.
|
||||
example_sequence = Rule {
|
||||
id = "01KQQ200000000000000000000"
|
||||
priority = 7
|
||||
when = EventPattern {
|
||||
type = "Sequence"
|
||||
kinds = [
|
||||
EventKind {tag = "BusAnnounce"}
|
||||
EventKind {tag = "BusInvoke"}
|
||||
]
|
||||
within_ms = 500
|
||||
}
|
||||
scope = Scope {}
|
||||
then = [
|
||||
Action {
|
||||
kind = "Log"
|
||||
level = "info"
|
||||
message = "patrón Announce→Invoke detectado <500ms"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
//! Audit log: cada acción mutadora del cerebro deja una entry inmutable
|
||||
//! con su predecesor encadenado por SHA256 (estilo Merkle). Verificable a
|
||||
//! posteriori sin confianza en quien escribe.
|
||||
//!
|
||||
//! Los entries viven en memoria. Para persistencia, `flush_to_cas()` los
|
||||
//! escribe al content-addressable store y devuelve el SHA del head, que
|
||||
//! puede guardarse en un archivo de "head pointer" (fuera de scope aquí).
|
||||
|
||||
use crate::crystallize::Crystal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::VecDeque;
|
||||
use ulid::Ulid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AuditEntry {
|
||||
/// Sequence number monotónico desde el inicio del log.
|
||||
pub seq: u64,
|
||||
/// Wall-clock al insertar.
|
||||
pub timestamp_ms: u64,
|
||||
/// SHA256 del entry anterior. None para el primer entry.
|
||||
pub prev_sha: Option<[u8; 32]>,
|
||||
/// SHA256 de este entry (auto-calculado al construir).
|
||||
pub sha: [u8; 32],
|
||||
/// Acción registrada.
|
||||
pub action: AuditAction,
|
||||
}
|
||||
|
||||
/// Sin `#[serde(tag)]`: bincode requiere external tagging (default serde
|
||||
/// para enums) para no usar `deserialize_any`. JSON sigue legible.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum AuditAction {
|
||||
PromoteCrystal { rule_id: Ulid, crystal: Crystal },
|
||||
RemoveRule { rule_id: Ulid },
|
||||
LoadRulesFile { path: String, count: usize },
|
||||
}
|
||||
|
||||
pub struct AuditLog {
|
||||
entries: VecDeque<AuditEntry>,
|
||||
next_seq: u64,
|
||||
/// Cap del log en memoria. Entries más viejos se descartan tras flush.
|
||||
cap: usize,
|
||||
/// Total acumulado de entries flusheadas a CAS.
|
||||
flushed_count: u64,
|
||||
/// SHA del último entry persistido a CAS — el "head pointer" del log.
|
||||
last_flushed_sha: Option<[u8; 32]>,
|
||||
/// Path opcional donde escribir el head pointer tras cada flush.
|
||||
head_pointer_path: Option<std::path::PathBuf>,
|
||||
/// Subscribers a entries en tiempo real. Cada `append` empuja a todos.
|
||||
/// Subscribers cuyo receiver se dropeó se purgan en el siguiente push.
|
||||
subscribers: Vec<tokio::sync::mpsc::UnboundedSender<AuditEntry>>,
|
||||
/// Wall-clock del último flush exitoso a CAS. None si aún no se flush.
|
||||
last_flush_at_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl AuditLog {
|
||||
pub fn new() -> Self {
|
||||
Self::with_cap(512)
|
||||
}
|
||||
|
||||
pub fn with_cap(cap: usize) -> Self {
|
||||
Self {
|
||||
entries: VecDeque::new(),
|
||||
next_seq: 0,
|
||||
cap,
|
||||
flushed_count: 0,
|
||||
last_flushed_sha: None,
|
||||
head_pointer_path: None,
|
||||
subscribers: Vec::new(),
|
||||
last_flush_at_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Registra un nuevo subscriber. El receiver recibe cada `AuditEntry`
|
||||
/// futuro hasta que el receiver se dropee (subscriber se purga al
|
||||
/// siguiente `append`).
|
||||
pub fn subscribe(&mut self) -> tokio::sync::mpsc::UnboundedReceiver<AuditEntry> {
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
self.subscribers.push(tx);
|
||||
rx
|
||||
}
|
||||
|
||||
pub fn subscriber_count(&self) -> usize { self.subscribers.len() }
|
||||
|
||||
pub fn with_head_pointer(mut self, path: std::path::PathBuf) -> Self {
|
||||
self.head_pointer_path = Some(path);
|
||||
self
|
||||
}
|
||||
|
||||
/// Apendea una acción. Calcula el SHA encadenado contra el último entry.
|
||||
pub fn append(&mut self, action: AuditAction) -> AuditEntry {
|
||||
let prev_sha = self.entries.back().map(|e| e.sha);
|
||||
let timestamp_ms = now_ms();
|
||||
let seq = self.next_seq;
|
||||
self.next_seq += 1;
|
||||
|
||||
// Pre-construct con sha en cero, luego calcular sha sobre el
|
||||
// serializado canónico, luego sobreescribir el campo.
|
||||
let mut entry = AuditEntry {
|
||||
seq, timestamp_ms, prev_sha, sha: [0u8; 32], action,
|
||||
};
|
||||
entry.sha = compute_sha(&entry);
|
||||
|
||||
if self.entries.len() >= self.cap {
|
||||
self.entries.pop_front();
|
||||
}
|
||||
self.entries.push_back(entry.clone());
|
||||
// Empujar a subscribers, purgando los muertos in-place.
|
||||
self.subscribers.retain(|tx| tx.send(entry.clone()).is_ok());
|
||||
entry
|
||||
}
|
||||
|
||||
pub fn recent(&self, limit: usize) -> impl Iterator<Item = &AuditEntry> {
|
||||
let n = if limit == 0 { self.entries.len() } else { limit.min(self.entries.len()) };
|
||||
self.entries.iter().skip(self.entries.len() - n)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize { self.entries.len() }
|
||||
pub fn is_empty(&self) -> bool { self.entries.is_empty() }
|
||||
|
||||
pub fn head_sha(&self) -> Option<[u8; 32]> {
|
||||
self.entries.back().map(|e| e.sha)
|
||||
}
|
||||
|
||||
/// Persiste el entry pasado al CAS y devuelve su SHA. Pensado para
|
||||
/// snapshots externos — el log en memoria sigue intacto.
|
||||
pub fn persist_to_cas(entry: &AuditEntry) -> anyhow::Result<[u8; 32]> {
|
||||
let bytes = serde_json::to_vec(entry)?;
|
||||
let sha = ente_cas::store(&bytes)?;
|
||||
Ok(sha)
|
||||
}
|
||||
|
||||
/// Persiste TODOS los entries actuales al CAS y actualiza el head pointer.
|
||||
/// Idempotente: re-flushar dos veces da los mismos SHAs (CAS dedup).
|
||||
/// Devuelve cuántas entries se flushearon en esta pasada.
|
||||
///
|
||||
/// Forma canónica: serializamos `entry` con `sha = [0; 32]` (formato
|
||||
/// pre-hash). El CAS computa sha256 sobre esos bytes y devuelve un SHA
|
||||
/// que por construcción coincide con `entry.sha` calculado al append.
|
||||
pub fn flush_to_cas(&mut self) -> anyhow::Result<usize> {
|
||||
let mut written = 0;
|
||||
let mut last_sha = self.last_flushed_sha;
|
||||
for entry in &self.entries {
|
||||
if entry.seq < self.flushed_count { continue; }
|
||||
let bytes = canonical_bytes(entry);
|
||||
let sha = ente_cas::store(&bytes)?;
|
||||
debug_assert_eq!(sha, entry.sha,
|
||||
"CAS sha != entry.sha — fórmula canónica rota");
|
||||
last_sha = Some(sha);
|
||||
written += 1;
|
||||
}
|
||||
self.flushed_count += written as u64;
|
||||
self.last_flushed_sha = last_sha;
|
||||
if written > 0 {
|
||||
self.last_flush_at_ms = Some(now_ms());
|
||||
}
|
||||
// Persistir head pointer si está configurado.
|
||||
if let (Some(path), Some(sha)) = (&self.head_pointer_path, last_sha) {
|
||||
let pointer = AuditHeadPointer {
|
||||
last_seq: self.next_seq.saturating_sub(1),
|
||||
last_sha: sha,
|
||||
flushed_count: self.flushed_count,
|
||||
timestamp_ms: now_ms(),
|
||||
};
|
||||
let json = serde_json::to_vec_pretty(&pointer)?;
|
||||
// Escritura atómica: tmp + rename
|
||||
let tmp = path.with_extension("tmp");
|
||||
if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
std::fs::write(&tmp, json)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
pub fn flushed_count(&self) -> u64 { self.flushed_count }
|
||||
pub fn last_flushed_sha(&self) -> Option<[u8; 32]> { self.last_flushed_sha }
|
||||
pub fn last_flush_at_ms(&self) -> Option<u64> { self.last_flush_at_ms }
|
||||
|
||||
/// Segundos transcurridos desde el último flush. None si nunca se flush.
|
||||
pub fn last_flush_age_secs(&self) -> Option<f64> {
|
||||
let then = self.last_flush_at_ms?;
|
||||
let now = now_ms();
|
||||
Some((now.saturating_sub(then)) as f64 / 1000.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer al head del audit log — escrito atómicamente en disco tras cada
|
||||
/// flush. Permite verificar la integridad del log sin escanearlo entero:
|
||||
/// el cliente lee el head, recupera el blob desde CAS, valida `prev_sha`
|
||||
/// recursivamente hasta el genesis.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AuditHeadPointer {
|
||||
pub last_seq: u64,
|
||||
pub last_sha: [u8; 32],
|
||||
pub flushed_count: u64,
|
||||
pub timestamp_ms: u64,
|
||||
}
|
||||
|
||||
/// Reporte de un replay: número de actions aplicadas + reglas finales.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ReplayReport {
|
||||
pub applied: u64,
|
||||
pub final_rule_count: usize,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Reporte de verificación de la cadena audit.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VerificationReport {
|
||||
/// Cuántas entries se recorrieron y verificaron exitosamente.
|
||||
pub verified: u64,
|
||||
/// Si hubo error, el seq donde se detectó.
|
||||
pub broken_at_seq: Option<u64>,
|
||||
/// Detalles del error si hubo.
|
||||
pub error: Option<String>,
|
||||
/// SHA del genesis (primer entry; prev_sha = None).
|
||||
pub genesis_sha: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// Recorre la cadena del audit log desde `start_sha` hacia atrás vía `prev_sha`
|
||||
/// hasta el genesis. Para cada entry valida:
|
||||
/// 1. CAS contiene un blob bajo ese SHA
|
||||
/// 2. sha256(blob) == SHA esperado (defensa contra tampering del CAS)
|
||||
/// 3. El blob deserializa a AuditEntry con sha=[0;32] (forma canónica)
|
||||
///
|
||||
/// Devuelve un VerificationReport con el conteo, posibles errores y
|
||||
/// el SHA del genesis (útil para clientes que quieren cachearlo).
|
||||
pub fn verify_chain_from_cas(start_sha: [u8; 32]) -> VerificationReport {
|
||||
let mut current = Some(start_sha);
|
||||
let mut verified = 0u64;
|
||||
let mut last_seen: Option<AuditEntry> = None;
|
||||
|
||||
while let Some(sha) = current {
|
||||
let path = ente_cas::cas_root().join(ente_cas::hex(&sha));
|
||||
let bytes = match std::fs::read(&path) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: last_seen.as_ref().map(|e| e.seq),
|
||||
error: Some(format!("CAS read {}: {e}", path.display())),
|
||||
genesis_sha: None,
|
||||
},
|
||||
};
|
||||
// Verificación 1: el blob hashea a la SHA esperada (CAS contract).
|
||||
let actual = ente_cas::sha256_of(&bytes);
|
||||
if actual != sha {
|
||||
return VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: last_seen.as_ref().map(|e| e.seq),
|
||||
error: Some(format!(
|
||||
"CAS tamper en {}: expected {} got {}",
|
||||
path.display(), ente_cas::hex(&sha), ente_cas::hex(&actual)
|
||||
)),
|
||||
genesis_sha: None,
|
||||
};
|
||||
}
|
||||
// Verificación 2: deserialize. El blob canónico tiene sha=[0;32].
|
||||
let mut entry: AuditEntry = match serde_json::from_slice(&bytes) {
|
||||
Ok(e) => e,
|
||||
Err(e) => return VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: last_seen.as_ref().map(|e| e.seq),
|
||||
error: Some(format!("deserialize: {e}")),
|
||||
genesis_sha: None,
|
||||
},
|
||||
};
|
||||
// Re-poblar el sha en el entry para reportar coherentemente.
|
||||
entry.sha = sha;
|
||||
verified += 1;
|
||||
|
||||
let prev = entry.prev_sha;
|
||||
last_seen = Some(entry);
|
||||
current = prev;
|
||||
}
|
||||
|
||||
VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: None,
|
||||
error: None,
|
||||
genesis_sha: last_seen.as_ref().map(|e| e.sha),
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve el set de SHAs alcanzables desde `start_sha` siguiendo
|
||||
/// `prev_sha` hasta el genesis. Usado por el GC del CAS para construir
|
||||
/// las "raíces vivas" del audit log.
|
||||
pub fn reachable_from_head(start_sha: [u8; 32]) -> std::collections::HashSet<[u8; 32]> {
|
||||
let mut set = std::collections::HashSet::new();
|
||||
let mut current = Some(start_sha);
|
||||
while let Some(sha) = current {
|
||||
if !set.insert(sha) { break; } // ciclo (no debería pasar) — corta
|
||||
let path = ente_cas::cas_root().join(ente_cas::hex(&sha));
|
||||
let bytes = match std::fs::read(&path) { Ok(b) => b, Err(_) => break };
|
||||
let entry: AuditEntry = match serde_json::from_slice(&bytes) {
|
||||
Ok(e) => e, Err(_) => break,
|
||||
};
|
||||
current = entry.prev_sha;
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// Recorre la cadena entera (head→genesis) y reconstruye la lista de
|
||||
/// actions en orden cronológico (oldest first). Útil tanto para replay
|
||||
/// como para auditoría retrospectiva.
|
||||
pub fn collect_chain_from_cas(start_sha: [u8; 32]) -> anyhow::Result<Vec<AuditEntry>> {
|
||||
let mut entries = Vec::new();
|
||||
let mut current = Some(start_sha);
|
||||
while let Some(sha) = current {
|
||||
let path = ente_cas::cas_root().join(ente_cas::hex(&sha));
|
||||
let bytes = std::fs::read(&path)?;
|
||||
let mut entry: AuditEntry = serde_json::from_slice(&bytes)?;
|
||||
entry.sha = sha;
|
||||
let prev = entry.prev_sha;
|
||||
entries.push(entry);
|
||||
current = prev;
|
||||
}
|
||||
// entries está en orden head→genesis. Reverse para chronological.
|
||||
entries.reverse();
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Aplica las actions de la cadena en orden cronológico contra un engine
|
||||
/// fresco. PromoteCrystal → insert. RemoveRule → remove. LoadRulesFile →
|
||||
/// log informativo (los archivos pueden no existir en el ambiente actual).
|
||||
pub fn replay_chain(
|
||||
start_sha: [u8; 32],
|
||||
engine: &mut crate::engine::RuleEngine,
|
||||
) -> ReplayReport {
|
||||
let entries = match collect_chain_from_cas(start_sha) {
|
||||
Ok(es) => es,
|
||||
Err(e) => return ReplayReport {
|
||||
applied: 0, final_rule_count: engine.len(),
|
||||
error: Some(format!("collect chain: {e}")),
|
||||
},
|
||||
};
|
||||
let mut applied = 0u64;
|
||||
for entry in &entries {
|
||||
match &entry.action {
|
||||
AuditAction::PromoteCrystal { rule_id, crystal } => {
|
||||
let mut rule = crate::crystallize::crystal_to_rule(crystal);
|
||||
rule.id = *rule_id; // preservar identidad histórica
|
||||
engine.insert(rule);
|
||||
}
|
||||
AuditAction::RemoveRule { rule_id } => {
|
||||
engine.remove(*rule_id);
|
||||
}
|
||||
AuditAction::LoadRulesFile { path: _, count: _ } => {
|
||||
// Los archivos referenciados por path pueden haber cambiado
|
||||
// o no existir. Log y skip — el replay sólo reconstruye
|
||||
// promotes/removes que tienen estado en CAS.
|
||||
}
|
||||
}
|
||||
applied += 1;
|
||||
}
|
||||
ReplayReport {
|
||||
applied,
|
||||
final_rule_count: engine.len(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AuditLog {
|
||||
fn default() -> Self { Self::new() }
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// SHA256 sobre el entry en forma canónica (sha=[0;32]). Hash y CAS storage
|
||||
/// ven los mismos bytes, así que `ente_cas::store(canonical)` devuelve el
|
||||
/// mismo SHA que `compute_sha(entry)`.
|
||||
fn compute_sha(entry: &AuditEntry) -> [u8; 32] {
|
||||
let bytes = canonical_bytes(entry);
|
||||
ente_cas::sha256_of(&bytes)
|
||||
}
|
||||
|
||||
/// Forma canónica: el entry serializado JSON con `sha = [0; 32]`.
|
||||
/// JSON sin pretty-print es determinístico para nuestros tipos.
|
||||
fn canonical_bytes(entry: &AuditEntry) -> Vec<u8> {
|
||||
let canonical = AuditEntry {
|
||||
sha: [0u8; 32],
|
||||
..entry.clone()
|
||||
};
|
||||
serde_json::to_vec(&canonical).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn chain_links_consecutive_entries() {
|
||||
let mut log = AuditLog::new();
|
||||
let e1 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
let e2 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
assert!(e1.prev_sha.is_none());
|
||||
assert_eq!(e2.prev_sha, Some(e1.sha));
|
||||
assert_ne!(e1.sha, e2.sha);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seq_monotonic() {
|
||||
let mut log = AuditLog::new();
|
||||
let e1 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
let e2 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
assert_eq!(e2.seq, e1.seq + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_evicts_oldest() {
|
||||
let mut log = AuditLog::with_cap(3);
|
||||
for _ in 0..5 {
|
||||
log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
}
|
||||
assert_eq!(log.len(), 3);
|
||||
// El primer seq superviviente debe ser 2.
|
||||
assert_eq!(log.recent(0).next().unwrap().seq, 2);
|
||||
}
|
||||
|
||||
// ---------- Tests de integración con CAS real (en directorio temporal) ----------
|
||||
|
||||
use crate::engine::RuleEngine;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Lock para serializar tests que mutan ENTE_CAS_ROOT (test threads
|
||||
/// comparten env vars). Sin esto, dos tests en paralelo pisan el path.
|
||||
static CAS_TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn with_temp_cas<F: FnOnce()>(f: F) {
|
||||
let _guard = CAS_TEST_LOCK.lock().unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("ente-cas-test-{}", Ulid::new()));
|
||||
std::env::set_var("ENTE_CAS_ROOT", &dir);
|
||||
let _cleanup = scopeguard(&dir);
|
||||
f();
|
||||
}
|
||||
|
||||
fn scopeguard(dir: &std::path::Path) -> impl Drop + '_ {
|
||||
struct G<'a>(&'a std::path::Path);
|
||||
impl<'a> Drop for G<'a> {
|
||||
fn drop(&mut self) {
|
||||
std::env::remove_var("ENTE_CAS_ROOT");
|
||||
let _ = std::fs::remove_dir_all(self.0);
|
||||
}
|
||||
}
|
||||
G(dir)
|
||||
}
|
||||
|
||||
fn dummy_crystal(ant: EventKind, con: EventKind) -> Crystal {
|
||||
Crystal {
|
||||
antecedent: ant,
|
||||
consequent: con,
|
||||
conditional_prob: 0.9,
|
||||
pmi: 1.5,
|
||||
support: 7,
|
||||
gap_stats: None,
|
||||
}
|
||||
}
|
||||
|
||||
use crate::rules::EventKind;
|
||||
|
||||
#[test]
|
||||
fn flush_round_trip_preserves_chain() {
|
||||
with_temp_cas(|| {
|
||||
let mut log = AuditLog::new();
|
||||
let id1 = Ulid::new();
|
||||
let id2 = Ulid::new();
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id1,
|
||||
crystal: dummy_crystal(EventKind::EnteSpawned, EventKind::EnteDied),
|
||||
});
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id2,
|
||||
crystal: dummy_crystal(EventKind::BusAnnounce, EventKind::BusInvoke),
|
||||
});
|
||||
log.append(AuditAction::RemoveRule { rule_id: id1 });
|
||||
|
||||
assert_eq!(log.flush_to_cas().unwrap(), 3);
|
||||
let head = log.last_flushed_sha().expect("head set");
|
||||
let report = verify_chain_from_cas(head);
|
||||
assert!(report.error.is_none(), "verification failed: {:?}", report.error);
|
||||
assert_eq!(report.verified, 3);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_reconstructs_engine_state() {
|
||||
with_temp_cas(|| {
|
||||
let mut log = AuditLog::new();
|
||||
let id1: Ulid = "01KQR3000000000000000000A1".parse().unwrap();
|
||||
let id2: Ulid = "01KQR3000000000000000000A2".parse().unwrap();
|
||||
let id3: Ulid = "01KQR3000000000000000000A3".parse().unwrap();
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id1,
|
||||
crystal: dummy_crystal(EventKind::EnteSpawned, EventKind::EnteDied),
|
||||
});
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id2,
|
||||
crystal: dummy_crystal(EventKind::BusAnnounce, EventKind::BusInvoke),
|
||||
});
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id3,
|
||||
crystal: dummy_crystal(EventKind::DeviceAdded, EventKind::DeviceRemoved),
|
||||
});
|
||||
log.append(AuditAction::RemoveRule { rule_id: id2 });
|
||||
log.flush_to_cas().unwrap();
|
||||
let head = log.last_flushed_sha().unwrap();
|
||||
|
||||
let mut engine = RuleEngine::empty();
|
||||
let rep = replay_chain(head, &mut engine);
|
||||
assert!(rep.error.is_none(), "replay error: {:?}", rep.error);
|
||||
assert_eq!(rep.applied, 4);
|
||||
assert_eq!(engine.len(), 2, "id2 should be removed, id1 + id3 remain");
|
||||
// Ulids preservados
|
||||
let ids: Vec<Ulid> = engine.rules().map(|r| r.id).collect();
|
||||
assert!(ids.contains(&id1));
|
||||
assert!(!ids.contains(&id2));
|
||||
assert!(ids.contains(&id3));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_after_eviction_still_works() {
|
||||
with_temp_cas(|| {
|
||||
// Cap pequeño: la mayoría de entries se evictan de memoria pero
|
||||
// siguen en CAS. Replay debe poder reconstruir desde CAS solo.
|
||||
let mut log = AuditLog::with_cap(2);
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..6 {
|
||||
let id = Ulid::new();
|
||||
ids.push(id);
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id,
|
||||
crystal: dummy_crystal(EventKind::EnteSpawned, EventKind::EnteDied),
|
||||
});
|
||||
log.flush_to_cas().unwrap();
|
||||
}
|
||||
assert_eq!(log.len(), 2, "cap eviction limita memoria");
|
||||
let head = log.last_flushed_sha().unwrap();
|
||||
|
||||
let mut engine = RuleEngine::empty();
|
||||
let rep = replay_chain(head, &mut engine);
|
||||
assert!(rep.error.is_none());
|
||||
assert_eq!(rep.applied, 6);
|
||||
assert_eq!(engine.len(), 6);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Autopromote loop. Background task que cada N segundos detecta cristales
|
||||
//! con thresholds altos y los promueve sin intervención humana.
|
||||
//!
|
||||
//! Anti-doble-promote: tras promover, registramos en un set la pareja
|
||||
//! (antecedent_kind, consequent_kind). Antes de promover, verificamos que
|
||||
//! no exista ya una regla con el mismo trigger_kind (heurística simple —
|
||||
//! evita ráfagas de duplicados de la misma estadística).
|
||||
|
||||
use crate::audit::AuditAction;
|
||||
use crate::crystallize::{crystal_to_rule, detect_crystals, Crystal, CrystallizationParams};
|
||||
use crate::introspect::{append_rule_jsonl, BrainState};
|
||||
use crate::rules::EventKind;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{info, warn};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AutopromoteParams {
|
||||
pub interval_secs: u64,
|
||||
pub threshold: CrystallizationParams,
|
||||
}
|
||||
|
||||
impl Default for AutopromoteParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
interval_secs: 60,
|
||||
// Más estrictos que el threshold default — evitar ruido.
|
||||
threshold: CrystallizationParams {
|
||||
min_support: 10,
|
||||
min_conditional_prob: 0.85,
|
||||
min_pmi: 2.0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn del bucle. El handle Mutex evita que dos pasadas concurrentes
|
||||
/// promuevan el mismo cristal (el lock garantiza serialización por brain).
|
||||
pub fn spawn_autopromote_loop(state: BrainState, params: AutopromoteParams) {
|
||||
let promoted_keys: Arc<Mutex<HashSet<(EventKind, EventKind)>>> =
|
||||
Arc::new(Mutex::new(HashSet::new()));
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(params.interval_secs));
|
||||
tick.tick().await; // descartar primer tick inmediato
|
||||
info!(?params, "autopromote loop activo");
|
||||
loop {
|
||||
tick.tick().await;
|
||||
run_one_pass(&state, ¶ms, &promoted_keys).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn run_one_pass(
|
||||
state: &BrainState,
|
||||
params: &AutopromoteParams,
|
||||
promoted_keys: &Arc<Mutex<HashSet<(EventKind, EventKind)>>>,
|
||||
) {
|
||||
let crystals: Vec<Crystal> = {
|
||||
let obs = state.observer.read().await;
|
||||
detect_crystals(&obs, ¶ms.threshold)
|
||||
};
|
||||
if crystals.is_empty() { return; }
|
||||
|
||||
let mut pk = promoted_keys.lock().await;
|
||||
for c in crystals {
|
||||
let key = (c.antecedent.clone(), c.consequent.clone());
|
||||
if pk.contains(&key) {
|
||||
// Ya promovido — el observer puede seguir reportando este
|
||||
// cristal pero no necesitamos otra regla.
|
||||
continue;
|
||||
}
|
||||
promote_one(state, &c).await;
|
||||
pk.insert(key);
|
||||
}
|
||||
}
|
||||
|
||||
async fn promote_one(state: &BrainState, c: &Crystal) {
|
||||
let rule = crystal_to_rule(c);
|
||||
let rule_id = rule.id;
|
||||
if let Some(path) = state.rules_out.as_ref() {
|
||||
if let Err(e) = append_rule_jsonl(path, &rule) {
|
||||
warn!(?e, "autopromote: rules_out append falló");
|
||||
}
|
||||
}
|
||||
state.engine.write().await.insert(rule);
|
||||
|
||||
state.audit.write().await.append(AuditAction::PromoteCrystal {
|
||||
rule_id,
|
||||
crystal: c.clone(),
|
||||
});
|
||||
info!(
|
||||
%rule_id,
|
||||
antecedent = ?c.antecedent,
|
||||
consequent = ?c.consequent,
|
||||
cp = c.conditional_prob,
|
||||
pmi = c.pmi,
|
||||
"autopromote: cristal → regla"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Cristalización: del flujo observado a reglas explícitas.
|
||||
//!
|
||||
//! Detecta pares (a, b) donde:
|
||||
//! - support(a, b) ≥ min_support (suficientes muestras para no ser ruido)
|
||||
//! - P(b|a) ≥ min_conditional_prob (a predice b con confianza)
|
||||
//! - PMI(a; b) ≥ min_pmi (más correlacionados que random)
|
||||
//!
|
||||
//! Cada cristal se materializa como `Rule` ejecutable (`crystal_to_rule`).
|
||||
//! Para persistencia/transporte, `crystal_to_json_pretty` serializa la Rule
|
||||
//! resultante con serde — sin formatos intermedios.
|
||||
|
||||
use crate::observer::{GapStats, Observer};
|
||||
use crate::rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Instant;
|
||||
use ulid::Ulid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Crystal {
|
||||
pub antecedent: EventKind,
|
||||
pub consequent: EventKind,
|
||||
pub conditional_prob: f64,
|
||||
pub pmi: f64,
|
||||
pub support: u64,
|
||||
/// Estadísticas del gap temporal entre antecedent → consequent.
|
||||
/// None si no hay histograma. Habilita generación de reglas Sequence
|
||||
/// con `within_ms = (mean + 2σ) * 1000`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub gap_stats: Option<GapStats>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct CrystallizationParams {
|
||||
pub min_support: u64,
|
||||
pub min_conditional_prob: f64,
|
||||
pub min_pmi: f64,
|
||||
}
|
||||
|
||||
impl Default for CrystallizationParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
min_support: 5,
|
||||
min_conditional_prob: 0.7,
|
||||
min_pmi: 0.5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detect_crystals(obs: &Observer, params: &CrystallizationParams) -> Vec<Crystal> {
|
||||
let mut out = Vec::new();
|
||||
for ((a, b), &count) in obs.cooccurrences() {
|
||||
if count < params.min_support { continue; }
|
||||
let cp = obs.conditional_prob(a, b);
|
||||
if cp < params.min_conditional_prob { continue; }
|
||||
let mi = obs.pmi(a, b);
|
||||
if mi < params.min_pmi { continue; }
|
||||
// Stats del histograma si existen para este par.
|
||||
let gap_stats = obs.gap_histograms()
|
||||
.get(&(a.clone(), b.clone()))
|
||||
.map(|h| h.stats());
|
||||
out.push(Crystal {
|
||||
antecedent: a.clone(),
|
||||
consequent: b.clone(),
|
||||
conditional_prob: cp,
|
||||
pmi: mi,
|
||||
support: count,
|
||||
gap_stats,
|
||||
});
|
||||
}
|
||||
out.sort_by(|x, y| y.conditional_prob.partial_cmp(&x.conditional_prob).unwrap_or(std::cmp::Ordering::Equal));
|
||||
out
|
||||
}
|
||||
|
||||
/// Serializa la `Rule` derivada del cristal como JSON pretty-printed. Ese
|
||||
/// JSON es el formato canónico de persistencia: el loader lo lee como una
|
||||
/// línea de JSONL o como elemento de un array. Los stats del cristal (P, PMI,
|
||||
/// support) viven en el audit log vía `AuditAction::PromoteCrystal`, no se
|
||||
/// duplican aquí.
|
||||
pub fn crystal_to_json_pretty(c: &Crystal) -> String {
|
||||
serde_json::to_string_pretty(&crystal_to_rule(c))
|
||||
.expect("Rule serialize should never fail")
|
||||
}
|
||||
|
||||
/// Convierte un cristal a una `Rule` ejecutable. Si hay gap_stats con
|
||||
/// muestras suficientes (≥ 4), genera una regla `Sequence` con
|
||||
/// `within_ms = (mean + 2σ) * 1000`. 2σ cubre ~95% de la distribución
|
||||
/// asumiendo normalidad — captura el "tiempo típico de respuesta" del
|
||||
/// patrón observado. Si no hay stats, fallback a `Single { antecedent }`.
|
||||
pub fn crystal_to_rule(c: &Crystal) -> Rule {
|
||||
let when = match &c.gap_stats {
|
||||
Some(s) if s.count >= 4 => {
|
||||
// Mínimo 1ms para evitar within_ms=0 cuando varianza colapsa.
|
||||
let bound_secs = (s.mean_secs + 2.0 * s.stddev_secs).max(0.001);
|
||||
EventPattern::Sequence {
|
||||
kinds: vec![c.antecedent.clone(), c.consequent.clone()],
|
||||
within_ms: (bound_secs * 1000.0).ceil() as u64,
|
||||
}
|
||||
}
|
||||
_ => EventPattern::Single { kind: c.antecedent.clone() },
|
||||
};
|
||||
let message = match &c.gap_stats {
|
||||
Some(s) if s.count >= 4 => format!(
|
||||
"crystal seq: {:?} → {:?} (P={:.2}, PMI={:.2}, gap={:.3}±{:.3}s)",
|
||||
c.antecedent, c.consequent, c.conditional_prob, c.pmi,
|
||||
s.mean_secs, s.stddev_secs,
|
||||
),
|
||||
_ => format!(
|
||||
"crystal: {:?} → {:?} (P={:.2}, PMI={:.2}, n={})",
|
||||
c.antecedent, c.consequent, c.conditional_prob, c.pmi, c.support
|
||||
),
|
||||
};
|
||||
Rule {
|
||||
id: Ulid::new(),
|
||||
priority: 5,
|
||||
when,
|
||||
scope: Scope::default(),
|
||||
then: vec![Action::Log { level: LogLevel::Info, message }],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// Patrones extendidos: Burst (alta frecuencia) y Silence (ausencia prolongada).
|
||||
// Estos cristales son sobre un único kind, no pares — capturan dinámicas
|
||||
// temporales de eventos individuales.
|
||||
// ============================================================================
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum PatternCrystal {
|
||||
/// Mismo evento aparece con frecuencia alta. `frequency_per_sec` se
|
||||
/// estima sobre el window de observación.
|
||||
Burst {
|
||||
kind: EventKind,
|
||||
count: u64,
|
||||
frequency_per_sec: f64,
|
||||
},
|
||||
/// Evento que dejó de aparecer. `since_secs` es el tiempo desde la
|
||||
/// última observación.
|
||||
Silence {
|
||||
kind: EventKind,
|
||||
last_count: u64,
|
||||
since_secs: f64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PatternParams {
|
||||
/// Mínimo de ocurrencias para considerar Burst.
|
||||
pub burst_min_count: u64,
|
||||
/// Frecuencia mínima (eventos por segundo) para considerar Burst.
|
||||
pub burst_min_freq_hz: f64,
|
||||
/// Tiempo desde última ocurrencia para considerar Silence.
|
||||
pub silence_min_secs: f64,
|
||||
/// Mínimo total previo para considerar Silence (eventos < N son ruido).
|
||||
pub silence_min_prior_count: u64,
|
||||
}
|
||||
|
||||
impl Default for PatternParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
burst_min_count: 10,
|
||||
burst_min_freq_hz: 5.0,
|
||||
silence_min_secs: 30.0,
|
||||
silence_min_prior_count: 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Detecta Bursts y Silences sobre la distribución marginal del observer.
|
||||
/// La frecuencia de un Burst se aproxima asumiendo que la observación cubre
|
||||
/// el rango entre `last_seen` y `Instant::now()` para ese kind.
|
||||
pub fn detect_pattern_crystals(obs: &Observer, params: &PatternParams) -> Vec<PatternCrystal> {
|
||||
let mut out = Vec::new();
|
||||
let now = Instant::now();
|
||||
for (kind, &count) in obs.marginals() {
|
||||
let last_seen = obs.last_seen_marginal(kind);
|
||||
// ---- Burst ----
|
||||
if count >= params.burst_min_count {
|
||||
// Aproximación: si vimos `count` eventos hasta `last_seen`, y el
|
||||
// primer evento sucedió en algún momento del window, la freq es
|
||||
// count / window_age. Sin tiempo del primer evento, usamos
|
||||
// last_seen → now como denominador (subestima freq) o asumimos
|
||||
// ventana fija de 60s. Usamos la última como aproximación.
|
||||
let elapsed = last_seen
|
||||
.map(|t| now.saturating_duration_since(t).as_secs_f64().max(0.001))
|
||||
.unwrap_or(60.0);
|
||||
// Estimación conservadora: count / max(window_age, 1s).
|
||||
// Si tenemos histograma, podríamos refinar — TODO.
|
||||
let freq = count as f64 / elapsed.max(1.0);
|
||||
if freq >= params.burst_min_freq_hz {
|
||||
out.push(PatternCrystal::Burst {
|
||||
kind: kind.clone(),
|
||||
count,
|
||||
frequency_per_sec: freq,
|
||||
});
|
||||
}
|
||||
}
|
||||
// ---- Silence ----
|
||||
if count >= params.silence_min_prior_count {
|
||||
if let Some(t) = last_seen {
|
||||
let since = now.saturating_duration_since(t).as_secs_f64();
|
||||
if since >= params.silence_min_secs {
|
||||
out.push(PatternCrystal::Silence {
|
||||
kind: kind.clone(),
|
||||
last_count: count,
|
||||
since_secs: since,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rules::EventKind::*;
|
||||
|
||||
#[test]
|
||||
fn detects_perfect_correlation() {
|
||||
let mut obs = Observer::new(100);
|
||||
for _ in 0..10 {
|
||||
obs.record(EnteSpawned);
|
||||
obs.record(EnteDied);
|
||||
}
|
||||
let crystals = detect_crystals(&obs, &CrystallizationParams {
|
||||
min_support: 3,
|
||||
min_conditional_prob: 0.5,
|
||||
min_pmi: 0.0,
|
||||
});
|
||||
assert!(crystals.iter().any(|c| matches!(c.antecedent, EnteSpawned)
|
||||
&& matches!(c.consequent, EnteDied)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_below_threshold() {
|
||||
let mut obs = Observer::new(100);
|
||||
// Sin co-ocurrencia significativa.
|
||||
for _ in 0..3 { obs.record(EnteSpawned); }
|
||||
let crystals = detect_crystals(&obs, &CrystallizationParams::default());
|
||||
assert!(crystals.is_empty(), "no debería haber cristales: {:?}", crystals);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Despacho asíncrono de Actions. El motor entrega `Vec<Arc<Rule>>` matched;
|
||||
//! este módulo las traduce a efectos del fractal vía un `ActionSink` trait.
|
||||
//!
|
||||
//! Esto invierte la dependencia: ente-brain no conoce a ente-zero. El init
|
||||
//! implementa `ActionSink` y wirea spawn/invoke/log a sus propias estructuras.
|
||||
|
||||
use crate::rules::{Action, LogLevel, Rule};
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
|
||||
/// Backend de ejecución de Actions. ente-zero implementa esto delegando a
|
||||
/// graph_tx (Spawn → SpawnRequest, Invoke → bus call, etc.).
|
||||
pub trait ActionSink: Send + Sync {
|
||||
/// Spawn una Card decodificada. Implementación: GraphEvent::SpawnRequest.
|
||||
fn spawn(&self, card_blob: &str);
|
||||
/// Invoke por bus. blob crudo; el sink lo enruta vía bus_mediator.
|
||||
fn invoke(&self, target_cap: ente_card::Capability, blob: Vec<u8>);
|
||||
/// Notifica a un Ente específico (target_id). Implementación: forward por bus.
|
||||
fn notify(&self, target_id: ulid::Ulid, message: &str);
|
||||
/// Inhibe un comportamiento (placeholder; semántica depende del sink).
|
||||
fn inhibit(&self, reason: &str);
|
||||
}
|
||||
|
||||
/// Sink por defecto que sólo logea. Útil para tests y dev sin runtime.
|
||||
pub struct NullSink;
|
||||
|
||||
impl ActionSink for NullSink {
|
||||
fn spawn(&self, card_blob: &str) {
|
||||
info!(blob_len = card_blob.len(), "NullSink::spawn (no-op)");
|
||||
}
|
||||
fn invoke(&self, target_cap: ente_card::Capability, blob: Vec<u8>) {
|
||||
info!(?target_cap, blob_len = blob.len(), "NullSink::invoke (no-op)");
|
||||
}
|
||||
fn notify(&self, target_id: ulid::Ulid, message: &str) {
|
||||
info!(%target_id, %message, "NullSink::notify (no-op)");
|
||||
}
|
||||
fn inhibit(&self, reason: &str) {
|
||||
info!(%reason, "NullSink::inhibit (no-op)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Ejecuta las reglas matched. Cada Rule puede tener N Actions; ejecutamos
|
||||
/// todas. Las acciones de Log se evalúan inline (tracing es async-safe).
|
||||
/// Las acciones de Spawn/Invoke/Notify se delegan al sink — el sink decide
|
||||
/// si procesarlas sincrónica o asincrónicamente.
|
||||
pub async fn dispatch_actions(rules: &[Arc<Rule>], sink: &dyn ActionSink) {
|
||||
for rule in rules {
|
||||
trace!(id = %rule.id, priority = rule.priority, n = rule.then.len(), "dispatching rule");
|
||||
for action in &rule.then {
|
||||
execute_action(action, sink, rule.id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_action(action: &Action, sink: &dyn ActionSink, rule_id: ulid::Ulid) {
|
||||
match action {
|
||||
Action::Log { level, message } => emit_log(level, message, rule_id),
|
||||
Action::Notify { target_id, message } => sink.notify(*target_id, message),
|
||||
Action::Spawn { card_blob } => sink.spawn(card_blob),
|
||||
Action::Invoke { target_cap, blob } => sink.invoke(target_cap.clone(), blob.clone()),
|
||||
Action::Inhibit { reason } => sink.inhibit(reason),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_log(level: &LogLevel, message: &str, rule_id: ulid::Ulid) {
|
||||
match level {
|
||||
LogLevel::Trace => trace!(rule = %rule_id, "{}", message),
|
||||
LogLevel::Debug => debug!(rule = %rule_id, "{}", message),
|
||||
LogLevel::Info => info! (rule = %rule_id, "{}", message),
|
||||
LogLevel::Warn => warn! (rule = %rule_id, "{}", message),
|
||||
LogLevel::Error => error!(rule = %rule_id, "{}", message),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Motor de inferencia. HashMap<EventKindDiscriminant, Vec<Arc<Rule>>> para
|
||||
//! lookup O(1) por tipo de evento, luego filter lineal por scope + filtros
|
||||
//! del payload (BusInvokeOf, Custom).
|
||||
//!
|
||||
//! Inmutabilidad fractal: `Arc<Rule>` es el unit de compartición. Clonar una
|
||||
//! regla del motor para entregarla al dispatcher es un refcount bump, no copia.
|
||||
|
||||
use crate::observer::TimedEvent;
|
||||
use crate::rules::{EventKind, EventPattern, Rule, Scope};
|
||||
use ente_card::Capability;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Discriminante barato de `EventKind` para indexar el HashMap. Sin payload —
|
||||
/// el match de payload se hace en una segunda pasada lineal en O(k) donde k
|
||||
/// es el número de reglas para ese tag.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum EventKindDiscriminant {
|
||||
EnteSpawned,
|
||||
EnteDied,
|
||||
BusAnnounce,
|
||||
BusInvoke,
|
||||
BusInvokeOf,
|
||||
DeviceAdded,
|
||||
DeviceRemoved,
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl From<&EventKind> for EventKindDiscriminant {
|
||||
fn from(k: &EventKind) -> Self {
|
||||
match k {
|
||||
EventKind::EnteSpawned => Self::EnteSpawned,
|
||||
EventKind::EnteDied => Self::EnteDied,
|
||||
EventKind::BusAnnounce => Self::BusAnnounce,
|
||||
EventKind::BusInvoke => Self::BusInvoke,
|
||||
EventKind::BusInvokeOf(_) => Self::BusInvokeOf,
|
||||
EventKind::DeviceAdded => Self::DeviceAdded,
|
||||
EventKind::DeviceRemoved => Self::DeviceRemoved,
|
||||
EventKind::Custom(_) => Self::Custom,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot del Ente que disparó el evento. Necesario para evaluar `Scope`.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SubjectInfo {
|
||||
pub id: Option<Ulid>,
|
||||
pub label: Option<String>,
|
||||
pub capabilities: Vec<Capability>,
|
||||
}
|
||||
|
||||
pub struct RuleEngine {
|
||||
rules: Vec<Arc<Rule>>,
|
||||
/// Reglas atómicas (Single, Sequence) indexadas por discriminante del
|
||||
/// kind que las dispara. Lookup O(1).
|
||||
by_kind: HashMap<EventKindDiscriminant, Vec<Arc<Rule>>>,
|
||||
/// Reglas compuestas (Either, All): se evalúan contra cada evento.
|
||||
/// Para fractales con N pequeño no afecta perf; con N grande, optimizar
|
||||
/// emitiendo a múltiples buckets en insert (fan-out).
|
||||
compound: Vec<Arc<Rule>>,
|
||||
}
|
||||
|
||||
impl Default for RuleEngine {
|
||||
fn default() -> Self { Self::empty() }
|
||||
}
|
||||
|
||||
impl RuleEngine {
|
||||
pub fn empty() -> Self {
|
||||
Self { rules: Vec::new(), by_kind: HashMap::new(), compound: Vec::new() }
|
||||
}
|
||||
|
||||
/// Carga reglas desde JSON (lista de Rule).
|
||||
pub fn load_json(json: &str) -> anyhow::Result<Self> {
|
||||
let rules: Vec<Rule> = serde_json::from_str(json)?;
|
||||
let mut engine = Self::empty();
|
||||
for r in rules {
|
||||
r.validate().map_err(|e| anyhow::anyhow!("regla inválida: {e}"))?;
|
||||
engine.insert(r);
|
||||
}
|
||||
Ok(engine)
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, rule: Rule) {
|
||||
let arc = Arc::new(rule);
|
||||
// Atómicas → bucket por discriminante. Compuestas → bucket fallback.
|
||||
if let Some(trigger) = arc.when.trigger_kind() {
|
||||
let disc = EventKindDiscriminant::from(trigger);
|
||||
self.by_kind.entry(disc).or_default().push(arc.clone());
|
||||
} else {
|
||||
self.compound.push(arc.clone());
|
||||
}
|
||||
self.rules.push(arc);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, id: Ulid) -> bool {
|
||||
let before = self.rules.len();
|
||||
self.rules.retain(|r| r.id != id);
|
||||
for v in self.by_kind.values_mut() {
|
||||
v.retain(|r| r.id != id);
|
||||
}
|
||||
self.compound.retain(|r| r.id != id);
|
||||
before != self.rules.len()
|
||||
}
|
||||
|
||||
pub fn rules(&self) -> impl Iterator<Item = &Arc<Rule>> { self.rules.iter() }
|
||||
|
||||
pub fn len(&self) -> usize { self.rules.len() }
|
||||
pub fn is_empty(&self) -> bool { self.rules.is_empty() }
|
||||
|
||||
/// Despacho determinista. Devuelve reglas que matchean, ordenadas por
|
||||
/// prioridad descendente. Cada Arc<Rule> se clona (refcount) — sin copiar
|
||||
/// los datos.
|
||||
///
|
||||
/// `history` es el slice de eventos recientes (en orden cronológico,
|
||||
/// más reciente al final) usado para evaluar Sequence patterns.
|
||||
/// Para reglas Single, history se ignora.
|
||||
///
|
||||
/// Si el evento es `BusInvokeOf(_)`, también consultamos el bucket
|
||||
/// `BusInvoke` (regla genérica que ignora la cap).
|
||||
pub fn dispatch(
|
||||
&self,
|
||||
event: &EventKind,
|
||||
subject: &SubjectInfo,
|
||||
history: &[TimedEvent],
|
||||
) -> Vec<Arc<Rule>> {
|
||||
let primary = EventKindDiscriminant::from(event);
|
||||
let mut buckets: Vec<&Vec<Arc<Rule>>> = Vec::with_capacity(2);
|
||||
if let Some(v) = self.by_kind.get(&primary) {
|
||||
buckets.push(v);
|
||||
}
|
||||
if matches!(event, EventKind::BusInvokeOf(_)) {
|
||||
if let Some(v) = self.by_kind.get(&EventKindDiscriminant::BusInvoke) {
|
||||
buckets.push(v);
|
||||
}
|
||||
}
|
||||
let mut hits: Vec<Arc<Rule>> = buckets.into_iter()
|
||||
.flat_map(|v| v.iter())
|
||||
.filter(|r| matches_pattern(&r.when, event, history))
|
||||
.filter(|r| matches_scope(&r.scope, subject))
|
||||
.cloned()
|
||||
.collect();
|
||||
// Fallback: reglas compuestas (Either/All) se evalúan siempre.
|
||||
for r in &self.compound {
|
||||
if matches_pattern(&r.when, event, history) && matches_scope(&r.scope, subject) {
|
||||
hits.push(r.clone());
|
||||
}
|
||||
}
|
||||
hits.sort_by(|a, b| b.priority.cmp(&a.priority));
|
||||
hits
|
||||
}
|
||||
}
|
||||
|
||||
/// Match recursivo del pattern. Atomic patterns evalúan contra el evento
|
||||
/// actual + history. Compuestos (Either/All) recursan sobre sus children.
|
||||
fn matches_pattern(pattern: &EventPattern, event: &EventKind, history: &[TimedEvent]) -> bool {
|
||||
match pattern {
|
||||
EventPattern::Single { kind } => matches_event_payload(kind, event),
|
||||
EventPattern::Sequence { kinds, within_ms } => {
|
||||
if kinds.is_empty() { return false; }
|
||||
let last_kind = kinds.last().unwrap();
|
||||
if !matches_event_payload(last_kind, event) { return false; }
|
||||
if history.len() < kinds.len() { return false; }
|
||||
let tail = &history[history.len() - kinds.len()..];
|
||||
for (t, k) in tail.iter().zip(kinds) {
|
||||
if !matches_event_payload(k, &t.kind) { return false; }
|
||||
}
|
||||
if *within_ms > 0 {
|
||||
let span = tail.last().unwrap().at.duration_since(tail.first().unwrap().at);
|
||||
if span > Duration::from_millis(*within_ms) { return false; }
|
||||
}
|
||||
true
|
||||
}
|
||||
EventPattern::Either { patterns } => {
|
||||
patterns.iter().any(|p| matches_pattern(p, event, history))
|
||||
}
|
||||
EventPattern::All { patterns } => {
|
||||
patterns.iter().all(|p| matches_pattern(p, event, history))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_event_payload(rule_kind: &EventKind, evt: &EventKind) -> bool {
|
||||
use EventKind::*;
|
||||
match (rule_kind, evt) {
|
||||
(EnteSpawned, EnteSpawned) => true,
|
||||
(EnteDied, EnteDied) => true,
|
||||
(BusAnnounce, BusAnnounce) => true,
|
||||
(BusInvoke, BusInvoke) | (BusInvoke, BusInvokeOf(_)) => true,
|
||||
(BusInvokeOf(want), BusInvokeOf(got)) => want == got,
|
||||
(DeviceAdded, DeviceAdded) => true,
|
||||
(DeviceRemoved, DeviceRemoved) => true,
|
||||
(Custom(want), Custom(got)) => want == got,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_scope(scope: &Scope, subj: &SubjectInfo) -> bool {
|
||||
if scope.is_wildcard() { return true; }
|
||||
if let Some(id) = scope.subject_id {
|
||||
if subj.id != Some(id) { return false; }
|
||||
}
|
||||
if let Some(lbl) = &scope.subject_label {
|
||||
if subj.label.as_ref() != Some(lbl) { return false; }
|
||||
}
|
||||
if let Some(cap) = &scope.subject_has_cap {
|
||||
if !subj.capabilities.contains(cap) { return false; }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rules::{Action, EventPattern, LogLevel};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn rule_single(id_str: &str, kind: EventKind, prio: u8) -> Rule {
|
||||
Rule {
|
||||
id: id_str.parse().unwrap(),
|
||||
priority: prio,
|
||||
when: EventPattern::Single { kind },
|
||||
then: vec![Action::Log {
|
||||
level: LogLevel::Info,
|
||||
message: id_str.into(),
|
||||
}],
|
||||
scope: Scope::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_history() -> Vec<TimedEvent> { Vec::new() }
|
||||
|
||||
#[test]
|
||||
fn dispatch_picks_only_matching_kind() {
|
||||
let mut e = RuleEngine::empty();
|
||||
e.insert(rule_single("01KQQ100000000000000000001", EventKind::EnteSpawned, 5));
|
||||
e.insert(rule_single("01KQQ100000000000000000002", EventKind::EnteDied, 5));
|
||||
let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &empty_history());
|
||||
assert_eq!(hits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn priority_orders_descending() {
|
||||
let mut e = RuleEngine::empty();
|
||||
e.insert(rule_single("01KQQ100000000000000000003", EventKind::EnteSpawned, 1));
|
||||
e.insert(rule_single("01KQQ100000000000000000004", EventKind::EnteSpawned, 9));
|
||||
let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &empty_history());
|
||||
assert_eq!(hits[0].priority, 9);
|
||||
assert_eq!(hits[1].priority, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_filters_by_label() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let mut r = rule_single("01KQQ100000000000000000005", EventKind::EnteSpawned, 5);
|
||||
r.scope = Scope { subject_label: Some("foo".into()), ..Default::default() };
|
||||
e.insert(r);
|
||||
let foo = SubjectInfo { label: Some("foo".into()), ..Default::default() };
|
||||
let bar = SubjectInfo { label: Some("bar".into()), ..Default::default() };
|
||||
assert_eq!(e.dispatch(&EventKind::EnteSpawned, &foo, &empty_history()).len(), 1);
|
||||
assert_eq!(e.dispatch(&EventKind::EnteSpawned, &bar, &empty_history()).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bus_invoke_generic_matches_specific() {
|
||||
let mut e = RuleEngine::empty();
|
||||
e.insert(rule_single("01KQQ100000000000000000006", EventKind::BusInvoke, 5));
|
||||
let hits = e.dispatch(
|
||||
&EventKind::BusInvokeOf(Capability::LegacyLogind),
|
||||
&SubjectInfo::default(),
|
||||
&empty_history(),
|
||||
);
|
||||
assert_eq!(hits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_pattern_matches_with_history() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000007".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 1000,
|
||||
},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
|
||||
let now = Instant::now();
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now },
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(50) },
|
||||
];
|
||||
let hits = e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history);
|
||||
assert_eq!(hits.len(), 1, "esperaba match secuencia, got {}", hits.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_outside_time_window() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000008".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 100,
|
||||
},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
let now = Instant::now();
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now },
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(500) },
|
||||
];
|
||||
let hits = e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history);
|
||||
assert!(hits.is_empty(), "no debería matchear fuera de la ventana");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_matches_any_branch() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000010".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Either { patterns: vec![
|
||||
EventPattern::Single { kind: EventKind::EnteSpawned },
|
||||
EventPattern::Single { kind: EventKind::EnteDied },
|
||||
]},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "either".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
assert_eq!(e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &[]).len(), 1);
|
||||
assert_eq!(e.dispatch(&EventKind::EnteDied, &SubjectInfo::default(), &[]).len(), 1);
|
||||
assert_eq!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &[]).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_requires_every_branch() {
|
||||
let mut e = RuleEngine::empty();
|
||||
// All: matchear sólo si el evento actual es BusAnnounce Y la
|
||||
// secuencia EnteSpawned→BusAnnounce ocurrió en history.
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000011".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::All { patterns: vec![
|
||||
EventPattern::Single { kind: EventKind::BusAnnounce },
|
||||
EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 0,
|
||||
},
|
||||
]},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "all".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
|
||||
let now = Instant::now();
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now },
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(10) },
|
||||
];
|
||||
// Single y Sequence ambos matchean → All matches.
|
||||
assert_eq!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history).len(), 1);
|
||||
// Sólo Single matchea (history vacío) → All no matches.
|
||||
assert!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_requires_correct_order() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000009".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 0,
|
||||
},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
let now = Instant::now();
|
||||
// Orden invertido en el history.
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now },
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now + Duration::from_millis(10) },
|
||||
];
|
||||
// El evento actual es EnteSpawned, pero el último de la secuencia
|
||||
// requerida es BusAnnounce — no debería matchear.
|
||||
let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &history);
|
||||
assert!(hits.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Introspect API. Unix Domain Socket + framing length-prefijo + bincode.
|
||||
//!
|
||||
//! Una herramienta externa (ej. `brainctl`) puede consultar el estado del
|
||||
//! cerebro sin tocar el bus interno del fractal. Esto separa observación de
|
||||
//! ejecución — la introspección es read-only por diseño.
|
||||
|
||||
use crate::crystallize::{detect_crystals, Crystal, CrystallizationParams};
|
||||
use crate::engine::RuleEngine;
|
||||
use crate::observer::Observer;
|
||||
use crate::rules::Rule;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{debug, info, trace, warn};
|
||||
use ulid::Ulid;
|
||||
|
||||
const MAX_FRAME: usize = 4 * 1024 * 1024; // 4 MiB — correlation matrices crecen
|
||||
|
||||
/// Estado compartido entre el bucle del Init y el servidor de introspección.
|
||||
/// `Arc<RwLock<...>>` permite muchos lectores concurrentes (introspect) y
|
||||
/// un escritor (el dispatcher de eventos en el bucle primordial).
|
||||
#[derive(Clone)]
|
||||
pub struct BrainState {
|
||||
pub engine: Arc<RwLock<RuleEngine>>,
|
||||
pub observer: Arc<RwLock<Observer>>,
|
||||
pub params: CrystallizationParams,
|
||||
/// Path opcional donde apendear reglas promovidas en JSONL. Si Some,
|
||||
/// cada PromoteCrystal añade una línea (append-only) con la Rule serializada.
|
||||
pub rules_out: Option<Arc<PathBuf>>,
|
||||
/// Audit log en memoria. Cada promote/remove deja huella aquí.
|
||||
pub audit: Arc<RwLock<crate::audit::AuditLog>>,
|
||||
}
|
||||
|
||||
impl BrainState {
|
||||
pub fn new(window_size: usize) -> Self {
|
||||
Self::with_params(window_size, CrystallizationParams::default())
|
||||
}
|
||||
|
||||
pub fn with_params(window_size: usize, params: CrystallizationParams) -> Self {
|
||||
Self {
|
||||
engine: Arc::new(RwLock::new(RuleEngine::empty())),
|
||||
observer: Arc::new(RwLock::new(Observer::new(window_size))),
|
||||
params,
|
||||
rules_out: None,
|
||||
audit: Arc::new(RwLock::new(crate::audit::AuditLog::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_rules_out(mut self, path: PathBuf) -> Self {
|
||||
self.rules_out = Some(Arc::new(path));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Append-only writer de una `Rule` serializada a `rules_out` en formato
|
||||
/// JSONL: una línea = un Rule JSON. Idempotente respecto a re-flushes
|
||||
/// porque el caller se encarga de no apendar la misma rule dos veces.
|
||||
/// El loader (`loader::extract_rules_from_json`) acepta tanto JSONL como
|
||||
/// arrays — el archivo es legible en ambos modos.
|
||||
pub fn append_rule_jsonl(path: &Path, rule: &Rule) -> std::io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)?;
|
||||
let line = serde_json::to_string(rule)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
writeln!(file, "{line}")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum IntrospectRequest {
|
||||
/// Lista resumida de reglas vivas.
|
||||
ListRules,
|
||||
/// Detalle de una regla concreta.
|
||||
GetRule(Ulid),
|
||||
/// Snapshot de la entropía y conteos básicos.
|
||||
EntropySnapshot,
|
||||
/// Top N pares (a, b) por co-ocurrencia.
|
||||
TopCorrelations { n: usize },
|
||||
/// Cristales detectados con los parámetros del BrainState.
|
||||
Crystals,
|
||||
/// Serializa la Rule derivada de un cristal específico como JSON
|
||||
/// (índice tras Crystals).
|
||||
CrystalJson { index: usize },
|
||||
/// Promueve el cristal #index a regla viva en el motor. Devuelve el
|
||||
/// rule_id asignado y el JSON de la Rule para auditoría/persistencia.
|
||||
PromoteCrystal { index: usize },
|
||||
/// Elimina una regla viva por id. Útil para revertir un promote.
|
||||
RemoveRule { id: Ulid },
|
||||
/// Lista las últimas N entradas del audit log. limit=0 = todas.
|
||||
ListAudit { limit: usize },
|
||||
/// Persiste todas las entries pendientes al CAS y actualiza el head
|
||||
/// pointer si el log lo tiene configurado.
|
||||
FlushAudit,
|
||||
/// Recarga reglas desde el archivo configurado por --rules-out (o el
|
||||
/// path provisto). Vacía el engine antes de cargar.
|
||||
ReloadRules { path: Option<String> },
|
||||
/// Verifica la cadena audit recorriendo prev_sha hasta el genesis,
|
||||
/// validando integridad de cada entry contra el CAS.
|
||||
VerifyAudit,
|
||||
/// Reconstruye el engine desde la cadena audit. Vacía engine y aplica
|
||||
/// PromoteCrystal/RemoveRule en orden cronológico.
|
||||
ReplayAudit,
|
||||
/// Mantiene la conexión abierta y empuja cada `AuditEntry` nuevo en
|
||||
/// frames `IntrospectResponse::AuditStreamFrame` hasta que el cliente
|
||||
/// cierra. Tras esta request no se aceptan más requests en la misma conn.
|
||||
StreamAudit,
|
||||
/// Garbage-collect el CAS. Considera reachable: todo lo alcanzable desde
|
||||
/// el head del audit log. Cualquier blob extra (Wasm modules referenciados
|
||||
/// por Cards) debe haberse pasado en `extra_roots` por el caller.
|
||||
GcCas { extra_roots: Vec<[u8; 32]> },
|
||||
/// Detecta cristales de patrones temporales (Burst, Silence).
|
||||
PatternCrystals,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum IntrospectResponse {
|
||||
Rules(Vec<RuleSummary>),
|
||||
Rule(Option<Rule>),
|
||||
Entropy { value_bits: f64, sample_size: u64, distinct_kinds: usize, window_full: bool },
|
||||
Correlations(Vec<CorrelationEntry>),
|
||||
Crystals(Vec<Crystal>),
|
||||
Json(String),
|
||||
/// Resultado de PromoteCrystal: id de la regla creada + JSON de la Rule
|
||||
/// para que el operador lo persista en disco si quiere.
|
||||
Promoted { rule_id: Ulid, rule_json: String },
|
||||
/// Resultado de RemoveRule: true si existía, false si ya no.
|
||||
Removed(bool),
|
||||
/// Entradas del audit log (más recientes al final).
|
||||
AuditEntries(Vec<crate::audit::AuditEntry>),
|
||||
/// Resultado de FlushAudit: cuántas entries se escribieron y SHA del head.
|
||||
Flushed { written: usize, head_sha: Option<[u8; 32]>, total_flushed: u64 },
|
||||
/// Resultado de ReloadRules: número total de reglas tras el reload.
|
||||
Reloaded { count: usize },
|
||||
/// Resultado de VerifyAudit.
|
||||
AuditVerified(crate::audit::VerificationReport),
|
||||
/// Resultado de ReplayAudit.
|
||||
Replayed(crate::audit::ReplayReport),
|
||||
/// Frame de streaming. El cliente lee estos en bucle hasta EOF.
|
||||
AuditStreamFrame(crate::audit::AuditEntry),
|
||||
/// Resultado de GcCas: cuántos blobs eliminados y bytes liberados.
|
||||
GcResult { deleted: usize, freed_bytes: u64 },
|
||||
/// Cristales de Burst/Silence detectados.
|
||||
Patterns(Vec<crate::crystallize::PatternCrystal>),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct RuleSummary {
|
||||
pub id: Ulid,
|
||||
pub priority: u8,
|
||||
pub event_kind_tag: String,
|
||||
pub action_count: usize,
|
||||
pub scope_wildcard: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct CorrelationEntry {
|
||||
pub a: String,
|
||||
pub b: String,
|
||||
pub joint_count: u64,
|
||||
pub conditional_prob: f64,
|
||||
pub pmi_bits: f64,
|
||||
}
|
||||
|
||||
pub struct IntrospectServer {
|
||||
state: BrainState,
|
||||
}
|
||||
|
||||
impl IntrospectServer {
|
||||
pub fn new(state: BrainState) -> Self { Self { state } }
|
||||
|
||||
/// Spawn del listener. Devuelve cuando bind() falla; en caso contrario
|
||||
/// corre indefinidamente.
|
||||
pub async fn serve(self, path: &Path) -> anyhow::Result<()> {
|
||||
let _ = std::fs::remove_file(path);
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let listener = UnixListener::bind(path)?;
|
||||
info!(path = %path.display(), "brain introspect escuchando");
|
||||
let arc_self = Arc::new(self);
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, _)) => {
|
||||
trace!("introspect conn aceptada");
|
||||
let me = arc_self.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = me.handle(stream).await {
|
||||
warn!(?e, "introspect conn ended");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "introspect accept failed");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(self: Arc<Self>, mut stream: UnixStream) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let mut len_buf = [0u8; 4];
|
||||
if stream.read_exact(&mut len_buf).await.is_err() {
|
||||
return Ok(()); // EOF
|
||||
}
|
||||
let len = u32::from_be_bytes(len_buf) as usize;
|
||||
if len > MAX_FRAME {
|
||||
anyhow::bail!("frame oversize: {len}");
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let req: IntrospectRequest = bincode::deserialize(&buf)?;
|
||||
debug!(?req, "introspect request");
|
||||
|
||||
// StreamAudit toma posesión de la conn — no más requests aquí.
|
||||
if matches!(req, IntrospectRequest::StreamAudit) {
|
||||
return self.stream_audit(stream).await;
|
||||
}
|
||||
|
||||
let resp = self.dispatch(req).await;
|
||||
|
||||
let out = bincode::serialize(&resp)?;
|
||||
stream.write_u32(out.len() as u32).await?;
|
||||
stream.write_all(&out).await?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Modo streaming: subscribe al audit log y empuja cada entry como
|
||||
/// frame `AuditStreamFrame`. La función retorna cuando el cliente
|
||||
/// cierra (write falla) o el subscriber se desconecta.
|
||||
async fn stream_audit(self: Arc<Self>, mut stream: UnixStream) -> anyhow::Result<()> {
|
||||
let mut rx = self.state.audit.write().await.subscribe();
|
||||
info!("audit stream client conectado");
|
||||
while let Some(entry) = rx.recv().await {
|
||||
let frame = IntrospectResponse::AuditStreamFrame(entry);
|
||||
let bytes = bincode::serialize(&frame)?;
|
||||
if stream.write_u32(bytes.len() as u32).await.is_err() { break; }
|
||||
if stream.write_all(&bytes).await.is_err() { break; }
|
||||
}
|
||||
info!("audit stream client desconectado");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn dispatch(&self, req: IntrospectRequest) -> IntrospectResponse {
|
||||
match req {
|
||||
IntrospectRequest::ListRules => {
|
||||
let engine = self.state.engine.read().await;
|
||||
let rules = engine.rules()
|
||||
.map(|r| RuleSummary {
|
||||
id: r.id,
|
||||
priority: r.priority,
|
||||
event_kind_tag: format!("{:?}", r.when),
|
||||
action_count: r.then.len(),
|
||||
scope_wildcard: r.scope.is_wildcard(),
|
||||
})
|
||||
.collect();
|
||||
IntrospectResponse::Rules(rules)
|
||||
}
|
||||
IntrospectRequest::GetRule(id) => {
|
||||
let engine = self.state.engine.read().await;
|
||||
let found = engine.rules()
|
||||
.find(|r| r.id == id)
|
||||
.map(|r| Rule::clone(r));
|
||||
IntrospectResponse::Rule(found)
|
||||
}
|
||||
IntrospectRequest::EntropySnapshot => {
|
||||
let obs = self.state.observer.read().await;
|
||||
IntrospectResponse::Entropy {
|
||||
value_bits: obs.shannon_entropy(),
|
||||
sample_size: obs.total(),
|
||||
distinct_kinds: obs.marginals().len(),
|
||||
window_full: obs.current_window() >= obs.window_size(),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::TopCorrelations { n } => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let mut entries: Vec<CorrelationEntry> = obs.cooccurrences().iter()
|
||||
.map(|((a, b), &joint)| CorrelationEntry {
|
||||
a: format!("{:?}", a),
|
||||
b: format!("{:?}", b),
|
||||
joint_count: joint,
|
||||
conditional_prob: obs.conditional_prob(a, b),
|
||||
pmi_bits: obs.pmi(a, b),
|
||||
})
|
||||
.collect();
|
||||
entries.sort_by(|x, y| y.joint_count.cmp(&x.joint_count));
|
||||
entries.truncate(n);
|
||||
IntrospectResponse::Correlations(entries)
|
||||
}
|
||||
IntrospectRequest::Crystals => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let crystals = detect_crystals(&obs, &self.state.params);
|
||||
IntrospectResponse::Crystals(crystals)
|
||||
}
|
||||
IntrospectRequest::CrystalJson { index } => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let crystals = detect_crystals(&obs, &self.state.params);
|
||||
match crystals.get(index) {
|
||||
Some(c) => IntrospectResponse::Json(crate::crystallize::crystal_to_json_pretty(c)),
|
||||
None => IntrospectResponse::Error(format!("no crystal at index {index}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::PromoteCrystal { index } => {
|
||||
let crystals = {
|
||||
let obs = self.state.observer.read().await;
|
||||
detect_crystals(&obs, &self.state.params)
|
||||
};
|
||||
match crystals.get(index) {
|
||||
Some(c) => {
|
||||
let rule = crate::crystallize::crystal_to_rule(c);
|
||||
let rule_id = rule.id;
|
||||
let rule_json = serde_json::to_string_pretty(&rule)
|
||||
.unwrap_or_else(|_| "<serialize failed>".into());
|
||||
self.state.engine.write().await.insert(rule.clone());
|
||||
// Persistencia opcional al archivo JSONL.
|
||||
if let Some(path) = self.state.rules_out.as_ref() {
|
||||
if let Err(e) = append_rule_jsonl(path, &rule) {
|
||||
warn!(?e, path = %path.display(), "rules_out append falló");
|
||||
} else {
|
||||
info!(path = %path.display(), %rule_id, "regla persistida a JSONL");
|
||||
}
|
||||
}
|
||||
// Audit entry
|
||||
self.state.audit.write().await.append(
|
||||
crate::audit::AuditAction::PromoteCrystal {
|
||||
rule_id, crystal: c.clone(),
|
||||
}
|
||||
);
|
||||
IntrospectResponse::Promoted { rule_id, rule_json }
|
||||
}
|
||||
None => IntrospectResponse::Error(format!("no crystal at index {index}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::RemoveRule { id } => {
|
||||
let removed = self.state.engine.write().await.remove(id);
|
||||
if removed {
|
||||
self.state.audit.write().await.append(
|
||||
crate::audit::AuditAction::RemoveRule { rule_id: id }
|
||||
);
|
||||
}
|
||||
IntrospectResponse::Removed(removed)
|
||||
}
|
||||
IntrospectRequest::ListAudit { limit } => {
|
||||
let audit = self.state.audit.read().await;
|
||||
IntrospectResponse::AuditEntries(audit.recent(limit).cloned().collect())
|
||||
}
|
||||
IntrospectRequest::FlushAudit => {
|
||||
let mut audit = self.state.audit.write().await;
|
||||
match audit.flush_to_cas() {
|
||||
Ok(written) => IntrospectResponse::Flushed {
|
||||
written,
|
||||
head_sha: audit.last_flushed_sha(),
|
||||
total_flushed: audit.flushed_count(),
|
||||
},
|
||||
Err(e) => IntrospectResponse::Error(format!("flush_to_cas: {e}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::VerifyAudit => {
|
||||
let head = self.state.audit.read().await.last_flushed_sha();
|
||||
let head = match head {
|
||||
Some(h) => h,
|
||||
None => return IntrospectResponse::Error(
|
||||
"audit log sin entries flushadas — nada que verificar".into()
|
||||
),
|
||||
};
|
||||
let report = crate::audit::verify_chain_from_cas(head);
|
||||
IntrospectResponse::AuditVerified(report)
|
||||
}
|
||||
IntrospectRequest::StreamAudit => {
|
||||
// Inalcanzable por construcción: handle() detecta StreamAudit
|
||||
// antes de llamar a dispatch(). Pero el match exige cubrir.
|
||||
IntrospectResponse::Error(
|
||||
"StreamAudit no debe llegar a dispatch — bug del handler".into()
|
||||
)
|
||||
}
|
||||
IntrospectRequest::PatternCrystals => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let params = crate::crystallize::PatternParams::default();
|
||||
let patterns = crate::crystallize::detect_pattern_crystals(&obs, ¶ms);
|
||||
IntrospectResponse::Patterns(patterns)
|
||||
}
|
||||
IntrospectRequest::GcCas { extra_roots } => {
|
||||
// Reachable = audit chain desde head + extra_roots provistos.
|
||||
let mut reachable = std::collections::HashSet::new();
|
||||
if let Some(head) = self.state.audit.read().await.last_flushed_sha() {
|
||||
reachable.extend(crate::audit::reachable_from_head(head));
|
||||
}
|
||||
reachable.extend(extra_roots);
|
||||
match ente_cas::gc(&reachable) {
|
||||
Ok((deleted, freed_bytes)) => IntrospectResponse::GcResult { deleted, freed_bytes },
|
||||
Err(e) => IntrospectResponse::Error(format!("gc: {e}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::ReplayAudit => {
|
||||
let head = self.state.audit.read().await.last_flushed_sha();
|
||||
let head = match head {
|
||||
Some(h) => h,
|
||||
None => return IntrospectResponse::Error(
|
||||
"audit log sin entries flushadas — nada que replayar".into()
|
||||
),
|
||||
};
|
||||
let mut engine = self.state.engine.write().await;
|
||||
*engine = crate::engine::RuleEngine::empty();
|
||||
let report = crate::audit::replay_chain(head, &mut engine);
|
||||
IntrospectResponse::Replayed(report)
|
||||
}
|
||||
IntrospectRequest::ReloadRules { path } => {
|
||||
// Path explícito gana sobre el rules_out configurado.
|
||||
let resolved = path.map(std::path::PathBuf::from)
|
||||
.or_else(|| self.state.rules_out.as_ref().map(|p| p.as_path().to_path_buf()));
|
||||
let path = match resolved {
|
||||
Some(p) => p,
|
||||
None => return IntrospectResponse::Error(
|
||||
"ReloadRules sin path y sin rules_out configurado".into()
|
||||
),
|
||||
};
|
||||
let rules = match crate::loader::load_rules_file(&path) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return IntrospectResponse::Error(format!("load: {e}")),
|
||||
};
|
||||
// Vaciamos el engine antes de re-cargar — semántica clean-slate.
|
||||
let mut engine = self.state.engine.write().await;
|
||||
*engine = crate::engine::RuleEngine::empty();
|
||||
let count = rules.len();
|
||||
for r in rules { engine.insert(r); }
|
||||
drop(engine);
|
||||
self.state.audit.write().await.append(
|
||||
crate::audit::AuditAction::LoadRulesFile {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
count,
|
||||
}
|
||||
);
|
||||
IntrospectResponse::Reloaded { count }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cliente helper para tools externos (brainctl).
|
||||
pub async fn call(path: &Path, req: IntrospectRequest) -> anyhow::Result<IntrospectResponse> {
|
||||
let mut stream = UnixStream::connect(path).await?;
|
||||
let buf = bincode::serialize(&req)?;
|
||||
stream.write_u32(buf.len() as u32).await?;
|
||||
stream.write_all(&buf).await?;
|
||||
|
||||
let mut len_buf = [0u8; 4];
|
||||
stream.read_exact(&mut len_buf).await?;
|
||||
let len = u32::from_be_bytes(len_buf) as usize;
|
||||
if len > MAX_FRAME {
|
||||
anyhow::bail!("response oversize: {len}");
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
Ok(bincode::deserialize(&buf)?)
|
||||
}
|
||||
|
||||
/// Consume la lista marginal del observer para humanos. Suprime el detalle
|
||||
/// crudo de `EventKind` (ej. payloads largos en BusInvokeOf).
|
||||
pub fn marginal_summary(obs: &Observer) -> Vec<(String, u64)> {
|
||||
let mut entries: Vec<(String, u64)> = obs.marginals().iter()
|
||||
.map(|(k, &c)| (format!("{:?}", k), c))
|
||||
.collect();
|
||||
entries.sort_by(|x, y| y.1.cmp(&x.1));
|
||||
entries
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! ente-brain: motor de reglas determinista + observador estadístico.
|
||||
//!
|
||||
//! Tres capas:
|
||||
//! 1. `rules` — tipos de regla (Triplet: Subject + Event + Action)
|
||||
//! 2. `engine` — RuleEngine con HashMap<EventKindDiscriminant, Vec<Arc<Rule>>>
|
||||
//! para dispatch O(1)
|
||||
//! 3. `dispatch` — ejecutor async de Actions (vía tokio)
|
||||
//! 4. `observer` — sliding window + marginales + co-ocurrencias
|
||||
//! + Shannon entropy + información mutua
|
||||
//! 5. `crystallize` — detección de patrones estadísticamente significativos
|
||||
//! y materialización en `Rule` ejecutables
|
||||
//! 6. `introspect` — Unix socket bincode API para tools externos
|
||||
//!
|
||||
//! Diseño de inmutabilidad:
|
||||
//! - Rules son `Arc<Rule>` — clonar es zero-copy (refcount bump).
|
||||
//! - El motor expone sólo lecturas; mutaciones pasan por `insert/remove`.
|
||||
//! - Observer mantiene contadores incrementales — sin recomputación.
|
||||
|
||||
pub mod audit;
|
||||
pub mod autopromote;
|
||||
pub mod crystallize;
|
||||
pub mod dispatch;
|
||||
pub mod engine;
|
||||
pub mod introspect;
|
||||
pub mod loader;
|
||||
pub mod metrics;
|
||||
pub mod observer;
|
||||
pub mod rules;
|
||||
|
||||
pub use autopromote::{spawn_autopromote_loop, AutopromoteParams};
|
||||
pub use crystallize::{detect_crystals, Crystal, CrystallizationParams};
|
||||
pub use dispatch::{dispatch_actions, ActionSink, NullSink};
|
||||
pub use engine::{EventKindDiscriminant, RuleEngine, SubjectInfo};
|
||||
pub use introspect::{IntrospectRequest, IntrospectResponse, IntrospectServer, BrainState};
|
||||
pub use loader::{load_card_file, load_rules_file};
|
||||
pub use metrics::serve_metrics;
|
||||
pub use observer::{Observer, TimedEvent};
|
||||
pub use rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Loader de Cards y Reglas desde archivos JSON.
|
||||
//!
|
||||
//! Sustituye al antiguo `kcl_loader.rs` (eliminado): la rama KCL invocaba
|
||||
//! un subprocess al CLI Go `kcl` que ningún target real tenía instalado y
|
||||
//! cuya validación duplicaba `EntityCard::validate()`. La fuente de verdad
|
||||
//! del shape de la Card es Rust + serde; en disco se guarda JSON crudo.
|
||||
//!
|
||||
//! Ergonomía de autoría futura (RON, Dhall, etc.) se añade como ramas
|
||||
//! adicionales aquí cuando duela escribir JSON a mano. Hoy: una sola rama.
|
||||
|
||||
use crate::rules::Rule;
|
||||
use ente_card::EntityCard;
|
||||
use std::path::Path;
|
||||
use tracing::info;
|
||||
|
||||
/// Carga una `EntityCard` desde un archivo JSON. Pasa por
|
||||
/// `EntityCard::validate()` antes de devolver — falla rápida.
|
||||
pub fn load_card_file(path: &Path) -> anyhow::Result<EntityCard> {
|
||||
info!(path = %path.display(), "cargando Card desde JSON");
|
||||
let raw = std::fs::read_to_string(path)?;
|
||||
let card = extract_card_from_json(&raw)?;
|
||||
card.validate()
|
||||
.map_err(|e| anyhow::anyhow!("Card inválida ({}): {e}", path.display()))?;
|
||||
Ok(card)
|
||||
}
|
||||
|
||||
/// Extrae una `EntityCard` de JSON. Acepta:
|
||||
/// 1. Object directamente serializable como EntityCard.
|
||||
/// 2. Object dict con un único valor que sea EntityCard (compat con
|
||||
/// salidas de generadores que envuelven en `{"seed": {...}}`).
|
||||
pub fn extract_card_from_json(raw: &str) -> anyhow::Result<EntityCard> {
|
||||
let v: serde_json::Value = serde_json::from_str(raw)?;
|
||||
let direct_err = match serde_json::from_value::<EntityCard>(v.clone()) {
|
||||
Ok(c) => return Ok(c),
|
||||
Err(e) => e,
|
||||
};
|
||||
if let serde_json::Value::Object(map) = v {
|
||||
for (_, vv) in map {
|
||||
if let Ok(c) = serde_json::from_value::<EntityCard>(vv) {
|
||||
return Ok(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Propagamos el error del intento directo: es el caso típico (JSON top-level
|
||||
// = EntityCard) y su mensaje apunta al campo concreto que rompió.
|
||||
anyhow::bail!("JSON no contiene una EntityCard válida: {direct_err}")
|
||||
}
|
||||
|
||||
/// Carga reglas desde un archivo JSON.
|
||||
pub fn load_rules_file(path: &Path) -> anyhow::Result<Vec<Rule>> {
|
||||
info!(path = %path.display(), "cargando reglas desde JSON");
|
||||
let raw = std::fs::read_to_string(path)?;
|
||||
extract_rules_from_json(&raw)
|
||||
}
|
||||
|
||||
/// Extrae un `Vec<Rule>` de un blob de texto. Acepta tres formas:
|
||||
/// 1. JSONL: una `Rule` por línea (el formato que escribe `append_rule_jsonl`).
|
||||
/// 2. Array directo: `[{...}, {...}]`.
|
||||
/// 3. Object con un campo array: `{"rules": [...]}`.
|
||||
///
|
||||
/// Heurística: si el primer carácter no-blanco es `[` o `{` con formato
|
||||
/// "objeto-con-array", parseamos como JSON único; en otro caso intentamos
|
||||
/// línea-por-línea. Líneas vacías o que empiecen con `#` se ignoran (compat
|
||||
/// con archivos editados a mano que dejen comentarios estilo shell).
|
||||
pub fn extract_rules_from_json(raw: &str) -> anyhow::Result<Vec<Rule>> {
|
||||
let trimmed_start = raw.trim_start();
|
||||
let looks_jsonl = trimmed_start.starts_with('{')
|
||||
&& raw.lines().filter(|l| {
|
||||
let t = l.trim();
|
||||
!t.is_empty() && !t.starts_with('#')
|
||||
}).count() > 1;
|
||||
|
||||
if !looks_jsonl {
|
||||
// Camino clásico: un único documento JSON (array o objeto).
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(raw) {
|
||||
let arr = match v {
|
||||
serde_json::Value::Array(_) => v,
|
||||
serde_json::Value::Object(map) => map
|
||||
.into_values()
|
||||
.find(|x| x.is_array())
|
||||
.ok_or_else(|| anyhow::anyhow!("JSON no contiene ningún array"))?,
|
||||
_ => anyhow::bail!("JSON debe ser array o object con campo array"),
|
||||
};
|
||||
return Ok(serde_json::from_value(arr)?);
|
||||
}
|
||||
// Caer a JSONL si el documento único no parsea — útil para archivos
|
||||
// que mezclan comentarios `#` (no JSON válido como documento único).
|
||||
}
|
||||
|
||||
let mut rules = Vec::new();
|
||||
for (idx, line) in raw.lines().enumerate() {
|
||||
let t = line.trim();
|
||||
if t.is_empty() || t.starts_with('#') { continue; }
|
||||
let rule: Rule = serde_json::from_str(t)
|
||||
.map_err(|e| anyhow::anyhow!("JSONL línea {}: {e}", idx + 1))?;
|
||||
rules.push(rule);
|
||||
}
|
||||
Ok(rules)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::introspect::append_rule_jsonl;
|
||||
use crate::rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
|
||||
use ulid::Ulid;
|
||||
|
||||
fn sample_rule() -> Rule {
|
||||
Rule {
|
||||
id: Ulid::new(),
|
||||
priority: 5,
|
||||
when: EventPattern::Single { kind: EventKind::EnteSpawned },
|
||||
then: vec![Action::Log {
|
||||
level: LogLevel::Info,
|
||||
message: "test".into(),
|
||||
}],
|
||||
scope: Scope::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_array() {
|
||||
let r = sample_rule();
|
||||
let raw = format!("[{}]", serde_json::to_string(&r).unwrap());
|
||||
let parsed = extract_rules_from_json(&raw).expect("array parse");
|
||||
assert_eq!(parsed.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_object_with_array() {
|
||||
let r = sample_rule();
|
||||
let raw = format!(r#"{{"rules":[{}]}}"#, serde_json::to_string(&r).unwrap());
|
||||
let parsed = extract_rules_from_json(&raw).expect("object parse");
|
||||
assert_eq!(parsed.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_jsonl_with_comments_and_blanks() {
|
||||
let r1 = sample_rule();
|
||||
let r2 = sample_rule();
|
||||
let raw = format!(
|
||||
"# header comment\n\n{}\n# inline comment\n{}\n\n",
|
||||
serde_json::to_string(&r1).unwrap(),
|
||||
serde_json::to_string(&r2).unwrap()
|
||||
);
|
||||
let parsed = extract_rules_from_json(&raw).expect("jsonl parse");
|
||||
assert_eq!(parsed.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_rule_jsonl_roundtrip() {
|
||||
let dir = tempdir_unique();
|
||||
let path = dir.join("rules.jsonl");
|
||||
let r1 = sample_rule();
|
||||
let r2 = sample_rule();
|
||||
append_rule_jsonl(&path, &r1).expect("append 1");
|
||||
append_rule_jsonl(&path, &r2).expect("append 2");
|
||||
let raw = std::fs::read_to_string(&path).expect("read back");
|
||||
let parsed = extract_rules_from_json(&raw).expect("roundtrip parse");
|
||||
assert_eq!(parsed.len(), 2);
|
||||
assert_eq!(parsed[0].id, r1.id);
|
||||
assert_eq!(parsed[1].id, r2.id);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn tempdir_unique() -> std::path::PathBuf {
|
||||
let base = std::env::temp_dir();
|
||||
let p = base.join(format!("ente-brain-loader-{}", Ulid::new()));
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
p
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Endpoint Prometheus en TCP. Formato text/plain (exposition format 0.0.4).
|
||||
//!
|
||||
//! Sin dependencias adicionales — la cardinalidad de nuestras métricas es
|
||||
//! pequeña y el formato es trivial. Si crece, sustituir por la crate
|
||||
//! `prometheus` con su Registry + encoders.
|
||||
|
||||
use crate::introspect::BrainState;
|
||||
use crate::rules::EventKind;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tracing::{info, trace, warn};
|
||||
|
||||
/// Lanza el listener Prometheus. Devuelve cuando bind() falla; en caso
|
||||
/// contrario corre indefinidamente. Pensado para `tokio::spawn`.
|
||||
pub async fn serve_metrics(state: BrainState, addr: SocketAddr) -> anyhow::Result<()> {
|
||||
let listener = TcpListener::bind(addr).await?;
|
||||
info!(?addr, "prometheus /metrics escuchando");
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, peer)) => {
|
||||
trace!(?peer, "metrics scrape");
|
||||
let s = state.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle_scrape(stream, s).await {
|
||||
warn!(?e, "metrics conn ended");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "metrics accept failed");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_scrape(mut stream: TcpStream, state: BrainState) -> anyhow::Result<()> {
|
||||
// Drenamos el request line + headers sin parsear (cualquier path
|
||||
// responde igual — Prometheus envía GET /metrics típicamente).
|
||||
let mut buf = [0u8; 1024];
|
||||
let _ = stream.read(&mut buf).await;
|
||||
let body = format_metrics(&state).await;
|
||||
let resp = format!(
|
||||
"HTTP/1.1 200 OK\r\n\
|
||||
Content-Type: text/plain; version=0.0.4\r\n\
|
||||
Content-Length: {}\r\n\
|
||||
Connection: close\r\n\
|
||||
\r\n\
|
||||
{}",
|
||||
body.len(), body
|
||||
);
|
||||
stream.write_all(resp.as_bytes()).await?;
|
||||
stream.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn format_metrics(state: &BrainState) -> String {
|
||||
let obs = state.observer.read().await;
|
||||
let engine = state.engine.read().await;
|
||||
let audit = state.audit.read().await;
|
||||
|
||||
let mut out = String::with_capacity(2048);
|
||||
|
||||
// ---- Entropía ----
|
||||
out.push_str("# HELP ente_brain_entropy_bits Shannon entropy of marginal event distribution.\n");
|
||||
out.push_str("# TYPE ente_brain_entropy_bits gauge\n");
|
||||
out.push_str(&format!("ente_brain_entropy_bits {:.6}\n", obs.shannon_entropy()));
|
||||
|
||||
// ---- Tamaño de muestra ----
|
||||
out.push_str("# HELP ente_brain_events_total Total events recorded by the observer.\n");
|
||||
out.push_str("# TYPE ente_brain_events_total counter\n");
|
||||
out.push_str(&format!("ente_brain_events_total {}\n", obs.total()));
|
||||
|
||||
// ---- Distinct kinds ----
|
||||
out.push_str("# HELP ente_brain_distinct_kinds Number of distinct EventKind tags seen.\n");
|
||||
out.push_str("# TYPE ente_brain_distinct_kinds gauge\n");
|
||||
out.push_str(&format!("ente_brain_distinct_kinds {}\n", obs.marginals().len()));
|
||||
|
||||
// ---- Window ocupación ----
|
||||
out.push_str("# HELP ente_brain_window_size Current sliding window length.\n");
|
||||
out.push_str("# TYPE ente_brain_window_size gauge\n");
|
||||
out.push_str(&format!("ente_brain_window_size {}\n", obs.current_window()));
|
||||
|
||||
// ---- Reglas vivas ----
|
||||
out.push_str("# HELP ente_brain_rules_active Number of rules currently in the engine.\n");
|
||||
out.push_str("# TYPE ente_brain_rules_active gauge\n");
|
||||
out.push_str(&format!("ente_brain_rules_active {}\n", engine.len()));
|
||||
|
||||
// ---- Eventos por kind ----
|
||||
out.push_str("# HELP ente_brain_events_by_kind Events by EventKind tag.\n");
|
||||
out.push_str("# TYPE ente_brain_events_by_kind counter\n");
|
||||
for (k, c) in obs.marginals() {
|
||||
out.push_str(&format!(
|
||||
"ente_brain_events_by_kind{{kind=\"{}\"}} {}\n",
|
||||
kind_label(k), c
|
||||
));
|
||||
}
|
||||
|
||||
// ---- Cristales detectados (con params actuales) ----
|
||||
let crystals = crate::detect_crystals(&obs, &state.params);
|
||||
out.push_str("# HELP ente_brain_crystals_total Number of crystals detected with current params.\n");
|
||||
out.push_str("# TYPE ente_brain_crystals_total gauge\n");
|
||||
out.push_str(&format!("ente_brain_crystals_total {}\n", crystals.len()));
|
||||
|
||||
// ---- Audit log ----
|
||||
out.push_str("# HELP ente_brain_audit_chain_length Total entries persisted to CAS.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_chain_length counter\n");
|
||||
out.push_str(&format!("ente_brain_audit_chain_length {}\n", audit.flushed_count()));
|
||||
|
||||
out.push_str("# HELP ente_brain_audit_in_memory Entries currently in the in-memory ring.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_in_memory gauge\n");
|
||||
out.push_str(&format!("ente_brain_audit_in_memory {}\n", audit.len()));
|
||||
|
||||
out.push_str("# HELP ente_brain_audit_subscribers Active stream-audit subscribers.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_subscribers gauge\n");
|
||||
out.push_str(&format!("ente_brain_audit_subscribers {}\n", audit.subscriber_count()));
|
||||
|
||||
if let Some(age) = audit.last_flush_age_secs() {
|
||||
out.push_str("# HELP ente_brain_audit_last_flush_age_seconds Time since last flush to CAS.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_last_flush_age_seconds gauge\n");
|
||||
out.push_str(&format!("ente_brain_audit_last_flush_age_seconds {:.3}\n", age));
|
||||
}
|
||||
if let Some(sha) = audit.last_flushed_sha() {
|
||||
// Info-style metric con head sha como label. Útil para dashboards
|
||||
// que quieran mostrar "current head".
|
||||
out.push_str("# HELP ente_brain_audit_head_info Current head SHA of the audit chain.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_head_info gauge\n");
|
||||
out.push_str(&format!(
|
||||
"ente_brain_audit_head_info{{sha=\"{}\"}} 1\n",
|
||||
ente_cas::hex(&sha)
|
||||
));
|
||||
}
|
||||
|
||||
// ---- Histogramas de gaps temporales (top-32 pares más frecuentes) ----
|
||||
out.push_str("# HELP ente_brain_pair_gap_seconds Time gap between correlated events.\n");
|
||||
out.push_str("# TYPE ente_brain_pair_gap_seconds histogram\n");
|
||||
let limits = crate::observer::GapHistogram::bucket_limits();
|
||||
for ((a, b), hist) in obs.top_gap_pairs(32) {
|
||||
let labels = format!(r#"a="{}",b="{}""#, kind_label(a), kind_label(b));
|
||||
for (i, &limit) in limits.iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_bucket{{{},le=\"{}\"}} {}\n",
|
||||
labels, limit, hist.buckets[i]
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_bucket{{{},le=\"+Inf\"}} {}\n",
|
||||
labels, hist.count
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_sum{{{}}} {:.6}\n",
|
||||
labels, hist.sum_secs
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_count{{{}}} {}\n",
|
||||
labels, hist.count
|
||||
));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn kind_label(k: &EventKind) -> &'static str {
|
||||
match k {
|
||||
EventKind::EnteSpawned => "EnteSpawned",
|
||||
EventKind::EnteDied => "EnteDied",
|
||||
EventKind::BusAnnounce => "BusAnnounce",
|
||||
EventKind::BusInvoke => "BusInvoke",
|
||||
EventKind::BusInvokeOf(_) => "BusInvokeOf",
|
||||
EventKind::DeviceAdded => "DeviceAdded",
|
||||
EventKind::DeviceRemoved => "DeviceRemoved",
|
||||
EventKind::Custom(_) => "Custom",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
//! Observador estadístico. Mantiene marginales y co-ocurrencias dentro de una
|
||||
//! ventana deslizante. Calcula entropía de Shannon e información mutua para
|
||||
//! identificar correlaciones significativas.
|
||||
//!
|
||||
//! Diseño:
|
||||
//! - Counters incrementales: cada `record()` es O(window_size) en el peor
|
||||
//! caso (actualiza co-ocurrencias con cada evento del window).
|
||||
//! - Sin recomputaciones globales: marginales y joint counts son state.
|
||||
//! - El cálculo de H(X), P(B|A), I(A;B) es O(|distinct events|).
|
||||
|
||||
use crate::rules::EventKind;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::time::Instant;
|
||||
|
||||
/// Evento timestamped. El timestamp se conserva para futuras políticas de
|
||||
/// expiración por tiempo (no sólo por count).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TimedEvent {
|
||||
pub kind: EventKind,
|
||||
pub at: Instant,
|
||||
}
|
||||
|
||||
/// Histograma de gaps temporales con buckets exponenciales en segundos.
|
||||
/// Cubre 6 órdenes de magnitud: 1ms hasta 1000s.
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GapHistogram {
|
||||
/// Buckets cumulativos (Prometheus-style): cada índice cuenta eventos
|
||||
/// con gap ≤ ese límite. Limites: 1ms, 10ms, 100ms, 1s, 10s, 100s, 1000s.
|
||||
pub buckets: [u64; 7],
|
||||
pub count: u64,
|
||||
pub sum_secs: f64,
|
||||
/// Suma de cuadrados — permite calcular varianza/stddev en O(1).
|
||||
pub sum_squares_secs: f64,
|
||||
pub max_secs: f64,
|
||||
}
|
||||
|
||||
/// Estadísticas resumidas de un GapHistogram, usables en cristales temporales.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GapStats {
|
||||
pub count: u64,
|
||||
pub mean_secs: f64,
|
||||
pub stddev_secs: f64,
|
||||
pub max_secs: f64,
|
||||
}
|
||||
|
||||
const GAP_BUCKET_LIMITS_SECS: [f64; 7] = [
|
||||
0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0,
|
||||
];
|
||||
|
||||
impl GapHistogram {
|
||||
pub fn observe(&mut self, gap_secs: f64) {
|
||||
for (i, &limit) in GAP_BUCKET_LIMITS_SECS.iter().enumerate() {
|
||||
if gap_secs <= limit {
|
||||
self.buckets[i] += 1;
|
||||
}
|
||||
}
|
||||
self.count += 1;
|
||||
self.sum_secs += gap_secs;
|
||||
self.sum_squares_secs += gap_secs * gap_secs;
|
||||
if gap_secs > self.max_secs { self.max_secs = gap_secs; }
|
||||
}
|
||||
|
||||
pub fn mean_secs(&self) -> f64 {
|
||||
if self.count == 0 { 0.0 } else { self.sum_secs / self.count as f64 }
|
||||
}
|
||||
|
||||
/// Desviación estándar muestral. Computada vía `sum_squares - n*mean²`
|
||||
/// para precisión razonable sin almacenar las muestras.
|
||||
pub fn stddev_secs(&self) -> f64 {
|
||||
if self.count < 2 { return 0.0; }
|
||||
let n = self.count as f64;
|
||||
let mean = self.mean_secs();
|
||||
let var = (self.sum_squares_secs - n * mean * mean) / (n - 1.0);
|
||||
// Numerical floor: var puede ser ligeramente negativo por float ε.
|
||||
if var <= 0.0 { 0.0 } else { var.sqrt() }
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> GapStats {
|
||||
GapStats {
|
||||
count: self.count,
|
||||
mean_secs: self.mean_secs(),
|
||||
stddev_secs: self.stddev_secs(),
|
||||
max_secs: self.max_secs,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bucket_limits() -> &'static [f64; 7] { &GAP_BUCKET_LIMITS_SECS }
|
||||
}
|
||||
|
||||
pub struct Observer {
|
||||
window: VecDeque<TimedEvent>,
|
||||
window_size: usize,
|
||||
marginal: HashMap<EventKind, u64>,
|
||||
cooccur: HashMap<(EventKind, EventKind), u64>,
|
||||
total: u64,
|
||||
/// Last-seen timestamps para aplicar decay en query time. None = sin
|
||||
/// time-decay (modo tradicional).
|
||||
last_seen_marginal: HashMap<EventKind, Instant>,
|
||||
last_seen_cooccur: HashMap<(EventKind, EventKind), Instant>,
|
||||
/// Half-life del decay exponencial en segundos. None = sin decay
|
||||
/// (las consultas devuelven los counts crudos).
|
||||
half_life_secs: Option<f64>,
|
||||
/// Histograma de gaps temporales por par (a, b). Capturado al `record()`.
|
||||
gap_histograms: HashMap<(EventKind, EventKind), GapHistogram>,
|
||||
/// Sets de "qué cambió desde el último snapshot". Se vacían en
|
||||
/// `snapshot()` y `snapshot_delta()`. Usado para escritura incremental.
|
||||
dirty_marginal: std::collections::HashSet<EventKind>,
|
||||
dirty_cooccur: std::collections::HashSet<(EventKind, EventKind)>,
|
||||
}
|
||||
|
||||
impl Observer {
|
||||
pub fn new(window_size: usize) -> Self {
|
||||
Self {
|
||||
window: VecDeque::with_capacity(window_size),
|
||||
window_size,
|
||||
marginal: HashMap::new(),
|
||||
cooccur: HashMap::new(),
|
||||
total: 0,
|
||||
last_seen_marginal: HashMap::new(),
|
||||
last_seen_cooccur: HashMap::new(),
|
||||
half_life_secs: None,
|
||||
gap_histograms: HashMap::new(),
|
||||
dirty_marginal: std::collections::HashSet::new(),
|
||||
dirty_cooccur: std::collections::HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Activa decay exponencial con half-life en segundos. λ = ln(2)/half_life.
|
||||
/// Aplicado en query time sobre los counts crudos usando last_seen.
|
||||
pub fn with_half_life(mut self, half_life_secs: f64) -> Self {
|
||||
if half_life_secs > 0.0 {
|
||||
self.half_life_secs = Some(half_life_secs);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn half_life(&self) -> Option<f64> { self.half_life_secs }
|
||||
|
||||
/// Registra un evento. Actualiza marginales y co-ocurrencias contra todo
|
||||
/// evento aún en la ventana.
|
||||
pub fn record(&mut self, kind: EventKind) {
|
||||
let now = Instant::now();
|
||||
let timed = TimedEvent { kind: kind.clone(), at: now };
|
||||
|
||||
// Co-ocurrencias: este evento con cada uno previo en ventana.
|
||||
// Capturamos también el gap temporal (now - w.at) para histograma.
|
||||
for w in &self.window {
|
||||
let key = (w.kind.clone(), kind.clone());
|
||||
*self.cooccur.entry(key.clone()).or_insert(0) += 1;
|
||||
self.last_seen_cooccur.insert(key.clone(), now);
|
||||
let gap_secs = now.duration_since(w.at).as_secs_f64();
|
||||
self.gap_histograms.entry(key.clone()).or_default().observe(gap_secs);
|
||||
self.dirty_cooccur.insert(key);
|
||||
}
|
||||
|
||||
self.window.push_back(timed);
|
||||
if self.window.len() > self.window_size {
|
||||
self.window.pop_front();
|
||||
}
|
||||
|
||||
*self.marginal.entry(kind.clone()).or_insert(0) += 1;
|
||||
self.last_seen_marginal.insert(kind.clone(), now);
|
||||
self.dirty_marginal.insert(kind);
|
||||
self.total += 1;
|
||||
}
|
||||
|
||||
/// Aplica el decay sobre un count crudo dado el `last_seen` correspondiente.
|
||||
/// Si half_life es None, devuelve el count tal cual (sin decay).
|
||||
fn decay(&self, count: u64, last_seen: Option<Instant>) -> f64 {
|
||||
let raw = count as f64;
|
||||
let (hl, last) = match (self.half_life_secs, last_seen) {
|
||||
(Some(hl), Some(t)) => (hl, t),
|
||||
_ => return raw,
|
||||
};
|
||||
let age_secs = Instant::now().duration_since(last).as_secs_f64();
|
||||
raw * 0.5_f64.powf(age_secs / hl)
|
||||
}
|
||||
|
||||
/// Marginal con decay aplicado.
|
||||
pub fn marginal_decayed(&self, k: &EventKind) -> f64 {
|
||||
let raw = self.marginal.get(k).copied().unwrap_or(0);
|
||||
let last = self.last_seen_marginal.get(k).copied();
|
||||
self.decay(raw, last)
|
||||
}
|
||||
|
||||
/// Cooccurrence con decay aplicado.
|
||||
pub fn cooccur_decayed(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
let raw = self.cooccur.get(&(a.clone(), b.clone())).copied().unwrap_or(0);
|
||||
let last = self.last_seen_cooccur.get(&(a.clone(), b.clone())).copied();
|
||||
self.decay(raw, last)
|
||||
}
|
||||
|
||||
/// Entropía de Shannon de la distribución marginal de eventos.
|
||||
/// H(X) = −Σ p(x) log₂ p(x). Unidad: bits.
|
||||
pub fn shannon_entropy(&self) -> f64 {
|
||||
if self.total == 0 { return 0.0; }
|
||||
let total = self.total as f64;
|
||||
self.marginal.values()
|
||||
.map(|&c| {
|
||||
let p = c as f64 / total;
|
||||
if p > 0.0 { -p * p.log2() } else { 0.0 }
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// P(b | a) = "dado que algo siguió a `a` dentro del window, qué fracción
|
||||
/// fue `b`". Suma 1 sobre todos los b posibles para un a fijo.
|
||||
///
|
||||
/// Implementación: cooccur_decayed(a, b) / Σ_x cooccur_decayed(a, x).
|
||||
/// Si half_life is None, los decayed values son los counts crudos.
|
||||
pub fn conditional_prob(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
let joint = self.cooccur_decayed(a, b);
|
||||
let row_total: f64 = self.cooccur.keys()
|
||||
.filter(|(x, _)| x == a)
|
||||
.map(|(x, y)| self.cooccur_decayed(x, y))
|
||||
.sum();
|
||||
if row_total <= 0.0 { 0.0 } else { joint / row_total }
|
||||
}
|
||||
|
||||
/// Información mutua puntual entre `a` y `b` con decay aplicado:
|
||||
/// PMI(a, b) = log₂( P(a, b) / (P(a) · P(b)) ).
|
||||
/// Positivo → más correlacionados de lo que sugiere independencia.
|
||||
pub fn pmi(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
// Total decayed: suma de marginales con decay (no usamos self.total
|
||||
// directo porque debería ser consistente con los decayed values).
|
||||
let total_decayed: f64 = self.marginal.keys()
|
||||
.map(|k| self.marginal_decayed(k))
|
||||
.sum();
|
||||
if total_decayed <= 0.0 { return 0.0; }
|
||||
let joint = self.cooccur_decayed(a, b) / total_decayed;
|
||||
let pa = self.marginal_decayed(a) / total_decayed;
|
||||
let pb = self.marginal_decayed(b) / total_decayed;
|
||||
if joint <= 0.0 || pa <= 0.0 || pb <= 0.0 { return 0.0; }
|
||||
(joint / (pa * pb)).log2()
|
||||
}
|
||||
|
||||
/// Información mutua acumulada de la pareja (a, b) ponderada por su
|
||||
/// probabilidad conjunta. Útil como medida de "interés" del par.
|
||||
pub fn weighted_pmi(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
if self.total == 0 { return 0.0; }
|
||||
let joint = self.cooccur
|
||||
.get(&(a.clone(), b.clone()))
|
||||
.copied()
|
||||
.unwrap_or(0) as f64 / self.total as f64;
|
||||
joint * self.pmi(a, b)
|
||||
}
|
||||
|
||||
pub fn marginals(&self) -> &HashMap<EventKind, u64> { &self.marginal }
|
||||
|
||||
/// Última vez que se vio un kind. None si nunca o si fue restaurado
|
||||
/// desde snapshot (los Instants no portables se descartan).
|
||||
pub fn last_seen_marginal(&self, kind: &EventKind) -> Option<Instant> {
|
||||
self.last_seen_marginal.get(kind).copied()
|
||||
}
|
||||
pub fn cooccurrences(&self) -> &HashMap<(EventKind, EventKind), u64> { &self.cooccur }
|
||||
pub fn total(&self) -> u64 { self.total }
|
||||
pub fn window_size(&self) -> usize { self.window_size }
|
||||
pub fn current_window(&self) -> usize { self.window.len() }
|
||||
|
||||
/// Últimos N eventos del window, en orden cronológico (más viejo primero).
|
||||
/// Si N > window.len(), devuelve todo el window.
|
||||
pub fn recent(&self, n: usize) -> impl Iterator<Item = &TimedEvent> {
|
||||
let start = self.window.len().saturating_sub(n);
|
||||
self.window.range(start..)
|
||||
}
|
||||
|
||||
pub fn gap_histograms(&self) -> &HashMap<(EventKind, EventKind), GapHistogram> {
|
||||
&self.gap_histograms
|
||||
}
|
||||
|
||||
/// Top-K pares por count del histograma (más frecuentes primero).
|
||||
/// Útil para limitar cardinalidad de métricas exportadas.
|
||||
pub fn top_gap_pairs(&self, k: usize) -> Vec<(&(EventKind, EventKind), &GapHistogram)> {
|
||||
let mut pairs: Vec<_> = self.gap_histograms.iter().collect();
|
||||
pairs.sort_by(|a, b| b.1.count.cmp(&a.1.count));
|
||||
pairs.truncate(k);
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Snapshot full: estado estadístico completo. Limpia los sets dirty
|
||||
/// como side-effect — los próximos `snapshot_delta()` cubren sólo los
|
||||
/// cambios posteriores.
|
||||
pub fn snapshot(&mut self) -> ObserverSnapshot {
|
||||
self.dirty_marginal.clear();
|
||||
self.dirty_cooccur.clear();
|
||||
ObserverSnapshot {
|
||||
schema_version: OBSERVER_SCHEMA_VERSION,
|
||||
is_delta: false,
|
||||
window_size: self.window_size,
|
||||
half_life_secs: self.half_life_secs,
|
||||
total: self.total,
|
||||
marginal: self.marginal.iter()
|
||||
.map(|(k, v)| (k.clone(), *v))
|
||||
.collect(),
|
||||
cooccur: self.cooccur.iter()
|
||||
.map(|((a, b), c)| (a.clone(), b.clone(), *c))
|
||||
.collect(),
|
||||
gap_histograms: self.gap_histograms.iter()
|
||||
.map(|((a, b), h)| (a.clone(), b.clone(), h.clone()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot incremental: sólo incluye los kinds y pares que cambiaron
|
||||
/// desde el último `snapshot()` o `snapshot_delta()`. Útil para
|
||||
/// checkpoints frecuentes con poco overhead. Limpia los sets dirty.
|
||||
pub fn snapshot_delta(&mut self) -> ObserverSnapshot {
|
||||
let marginal: Vec<_> = self.dirty_marginal.iter()
|
||||
.filter_map(|k| self.marginal.get(k).map(|v| (k.clone(), *v)))
|
||||
.collect();
|
||||
let cooccur: Vec<_> = self.dirty_cooccur.iter()
|
||||
.filter_map(|(a, b)| {
|
||||
self.cooccur.get(&(a.clone(), b.clone()))
|
||||
.map(|c| (a.clone(), b.clone(), *c))
|
||||
})
|
||||
.collect();
|
||||
// Para histogramas: incluimos los pares cuyo cooccur cambió.
|
||||
let gap_histograms: Vec<_> = self.dirty_cooccur.iter()
|
||||
.filter_map(|(a, b)| {
|
||||
self.gap_histograms.get(&(a.clone(), b.clone()))
|
||||
.map(|h| (a.clone(), b.clone(), h.clone()))
|
||||
})
|
||||
.collect();
|
||||
self.dirty_marginal.clear();
|
||||
self.dirty_cooccur.clear();
|
||||
ObserverSnapshot {
|
||||
schema_version: OBSERVER_SCHEMA_VERSION,
|
||||
is_delta: true,
|
||||
window_size: self.window_size,
|
||||
half_life_secs: self.half_life_secs,
|
||||
total: self.total,
|
||||
marginal, cooccur, gap_histograms,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aplica un delta sobre el estado actual. Para `is_delta=true`, los
|
||||
/// valores en marginal/cooccur sobrescriben las entradas existentes.
|
||||
/// Si `is_delta=false`, equivale a `from_snapshot` pero in-place.
|
||||
pub fn apply_delta(&mut self, delta: ObserverSnapshot) {
|
||||
let now = Instant::now();
|
||||
if !delta.is_delta {
|
||||
// Full: reset state.
|
||||
*self = Self::from_snapshot(delta);
|
||||
return;
|
||||
}
|
||||
// Incremental merge.
|
||||
for (k, v) in delta.marginal {
|
||||
self.last_seen_marginal.insert(k.clone(), now);
|
||||
self.marginal.insert(k, v);
|
||||
}
|
||||
for (a, b, c) in delta.cooccur {
|
||||
self.last_seen_cooccur.insert((a.clone(), b.clone()), now);
|
||||
self.cooccur.insert((a, b), c);
|
||||
}
|
||||
for (a, b, h) in delta.gap_histograms {
|
||||
self.gap_histograms.insert((a, b), h);
|
||||
}
|
||||
// total: sólo subimos (el delta podría estar atrasado).
|
||||
if delta.total > self.total { self.total = delta.total; }
|
||||
}
|
||||
|
||||
/// Reconstruye Observer desde un snapshot. El window queda vacío;
|
||||
/// last_seen_* se inicializa en `now()` para que el decay arranque
|
||||
/// "ahora" para todos los counts (aproximación razonable post-reboot).
|
||||
pub fn from_snapshot(snap: ObserverSnapshot) -> Self {
|
||||
let now = Instant::now();
|
||||
let mut marginal = HashMap::new();
|
||||
let mut last_seen_marginal = HashMap::new();
|
||||
for (k, v) in snap.marginal {
|
||||
last_seen_marginal.insert(k.clone(), now);
|
||||
marginal.insert(k, v);
|
||||
}
|
||||
let mut cooccur = HashMap::new();
|
||||
let mut last_seen_cooccur = HashMap::new();
|
||||
for (a, b, c) in snap.cooccur {
|
||||
last_seen_cooccur.insert((a.clone(), b.clone()), now);
|
||||
cooccur.insert((a, b), c);
|
||||
}
|
||||
let gap_histograms = snap.gap_histograms.into_iter()
|
||||
.map(|(a, b, h)| ((a, b), h))
|
||||
.collect();
|
||||
Self {
|
||||
window: VecDeque::with_capacity(snap.window_size),
|
||||
window_size: snap.window_size,
|
||||
marginal,
|
||||
cooccur,
|
||||
total: snap.total,
|
||||
last_seen_marginal,
|
||||
last_seen_cooccur,
|
||||
half_life_secs: snap.half_life_secs,
|
||||
gap_histograms,
|
||||
dirty_marginal: std::collections::HashSet::new(),
|
||||
dirty_cooccur: std::collections::HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const OBSERVER_SCHEMA_VERSION: u16 = 1;
|
||||
|
||||
/// Snapshot serializable. Se persiste a JSON en disco y se restaura al
|
||||
/// reboot para preservar contadores, co-ocurrencias e histogramas.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ObserverSnapshot {
|
||||
pub schema_version: u16,
|
||||
/// `true` si sólo contiene los cambios desde el último snapshot.
|
||||
/// `false` = full state, sobreescribe el observer al aplicar.
|
||||
#[serde(default)]
|
||||
pub is_delta: bool,
|
||||
pub window_size: usize,
|
||||
pub half_life_secs: Option<f64>,
|
||||
pub total: u64,
|
||||
/// Marginales serializados como Vec porque HashMap<EventKind, _> usa
|
||||
/// EventKind como key — y EventKind tiene variantes con payloads que
|
||||
/// no son JSON-key-serializable (BusInvokeOf, Custom).
|
||||
pub marginal: Vec<(EventKind, u64)>,
|
||||
pub cooccur: Vec<(EventKind, EventKind, u64)>,
|
||||
pub gap_histograms: Vec<(EventKind, EventKind, GapHistogram)>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rules::EventKind::*;
|
||||
|
||||
#[test]
|
||||
fn entropy_zero_for_single_event() {
|
||||
let mut obs = Observer::new(10);
|
||||
for _ in 0..5 { obs.record(EnteSpawned); }
|
||||
// Distribución degenerada: una sola observación posible → H = 0.
|
||||
assert!(obs.shannon_entropy() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entropy_one_for_balanced_binary() {
|
||||
let mut obs = Observer::new(100);
|
||||
for _ in 0..10 { obs.record(EnteSpawned); }
|
||||
for _ in 0..10 { obs.record(EnteDied); }
|
||||
// Bernoulli(0.5) → H = 1 bit.
|
||||
assert!((obs.shannon_entropy() - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_prob_perfect_dependency() {
|
||||
let mut obs = Observer::new(100);
|
||||
// Spawned siempre seguido por Died.
|
||||
for _ in 0..5 {
|
||||
obs.record(EnteSpawned);
|
||||
obs.record(EnteDied);
|
||||
}
|
||||
let p = obs.conditional_prob(&EnteSpawned, &EnteDied);
|
||||
assert!(p > 0.0, "esperamos correlación positiva, got {p}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Tipos de regla. La fuente de verdad del shape es esta definición Rust;
|
||||
//! `schema/rule.k` queda como referencia de diseño no cargada.
|
||||
//!
|
||||
//! Cargables desde JSON (array, objeto-con-array, o JSONL). El motor no
|
||||
//! acepta Rules construidas a mano sin pasar por validate() — ver
|
||||
//! `engine::insert`.
|
||||
|
||||
use ente_card::Capability;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Triplet [Sujeto + Evento + Acción]. Inmutable tras carga.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Rule {
|
||||
pub id: Ulid,
|
||||
#[serde(default = "default_priority")]
|
||||
pub priority: u8,
|
||||
pub when: EventPattern,
|
||||
pub then: Vec<Action>,
|
||||
#[serde(default)]
|
||||
pub scope: Scope,
|
||||
}
|
||||
|
||||
fn default_priority() -> u8 { 5 }
|
||||
|
||||
impl Rule {
|
||||
pub fn validate(&self) -> Result<(), RuleError> {
|
||||
if self.then.is_empty() {
|
||||
return Err(RuleError::EmptyActions);
|
||||
}
|
||||
self.when.validate_recursive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RuleError {
|
||||
EmptyActions,
|
||||
EmptySequence,
|
||||
EmptyCompound,
|
||||
InvalidPriority,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RuleError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::EmptyActions => write!(f, "regla sin acciones"),
|
||||
Self::EmptySequence => write!(f, "Sequence pattern con kinds vacío"),
|
||||
Self::EmptyCompound => write!(f, "Either/All con patterns vacío"),
|
||||
Self::InvalidPriority => write!(f, "prioridad fuera de rango"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RuleError {}
|
||||
|
||||
/// Match del sujeto. Vacío en todos los campos = match cualquier Ente.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Scope {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub subject_id: Option<Ulid>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub subject_label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub subject_has_cap: Option<Capability>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub fn is_wildcard(&self) -> bool {
|
||||
self.subject_id.is_none()
|
||||
&& self.subject_label.is_none()
|
||||
&& self.subject_has_cap.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Patrón de evento que dispara una regla. Tagged union — JSON con campo
|
||||
/// `type`. Soporta composición recursiva (Either/All) sobre Single y
|
||||
/// Sequence atómicos.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum EventPattern {
|
||||
/// Match un único evento por kind.
|
||||
Single { kind: EventKind },
|
||||
/// Match si los últimos N eventos del history coinciden en orden con
|
||||
/// `kinds`, todos dentro de `within_ms` (0 = sin límite temporal).
|
||||
Sequence {
|
||||
kinds: Vec<EventKind>,
|
||||
#[serde(default)]
|
||||
within_ms: u64,
|
||||
},
|
||||
/// OR: match si cualquier sub-pattern matchea.
|
||||
Either { patterns: Vec<EventPattern> },
|
||||
/// AND: match si todos los sub-patterns matchean simultáneamente
|
||||
/// contra el mismo (event, history).
|
||||
All { patterns: Vec<EventPattern> },
|
||||
}
|
||||
|
||||
impl EventPattern {
|
||||
/// `true` si el pattern es atómico (no recursivo) y puede ser indexado
|
||||
/// por discriminante de `EventKind` para dispatch O(1). Compuestos
|
||||
/// (Either/All) se evalúan en un bucket de fallback.
|
||||
pub fn is_simple(&self) -> bool {
|
||||
matches!(self, Self::Single { .. } | Self::Sequence { .. })
|
||||
}
|
||||
|
||||
/// Última `EventKind` que dispara la evaluación de un pattern atómico.
|
||||
/// Devuelve None para compuestos.
|
||||
pub fn trigger_kind(&self) -> Option<&EventKind> {
|
||||
match self {
|
||||
Self::Single { kind } => Some(kind),
|
||||
Self::Sequence { kinds, .. } => kinds.last(),
|
||||
Self::Either { .. } | Self::All { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validación recursiva. Compuestos vacíos se rechazan al cargar.
|
||||
pub fn validate_recursive(&self) -> Result<(), RuleError> {
|
||||
match self {
|
||||
Self::Single { .. } => Ok(()),
|
||||
Self::Sequence { kinds, .. } => {
|
||||
if kinds.is_empty() { Err(RuleError::EmptySequence) } else { Ok(()) }
|
||||
}
|
||||
Self::Either { patterns } | Self::All { patterns } => {
|
||||
if patterns.is_empty() {
|
||||
return Err(RuleError::EmptyCompound);
|
||||
}
|
||||
for p in patterns { p.validate_recursive()?; }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tipo de evento que dispara reglas. Indexado por discriminante en el motor.
|
||||
/// Diseñado para que `EventKindDiscriminant::from(&kind)` sea barato (no hash
|
||||
/// del payload, sólo del tag).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub enum EventKind {
|
||||
EnteSpawned,
|
||||
EnteDied,
|
||||
BusAnnounce,
|
||||
BusInvoke,
|
||||
BusInvokeOf(Capability),
|
||||
DeviceAdded,
|
||||
DeviceRemoved,
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum LogLevel { Trace, Debug, Info, Warn, Error }
|
||||
|
||||
impl LogLevel {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Trace => "trace",
|
||||
Self::Debug => "debug",
|
||||
Self::Info => "info",
|
||||
Self::Warn => "warn",
|
||||
Self::Error => "error",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "PascalCase")]
|
||||
pub enum Action {
|
||||
Log {
|
||||
#[serde(default = "default_log_level")]
|
||||
level: LogLevel,
|
||||
message: String,
|
||||
},
|
||||
Notify {
|
||||
target_id: Ulid,
|
||||
message: String,
|
||||
},
|
||||
/// `card_blob` es JSON del EntityCard codificado en base64. El motor lo
|
||||
/// decodifica y forwarda como SpawnRequest al graph.
|
||||
Spawn {
|
||||
card_blob: String,
|
||||
},
|
||||
Invoke {
|
||||
target_cap: Capability,
|
||||
/// blob crudo (en JSON viaja como base64 vía `blob_b64`).
|
||||
#[serde(with = "blob_b64")]
|
||||
blob: Vec<u8>,
|
||||
},
|
||||
Inhibit {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_log_level() -> LogLevel { LogLevel::Info }
|
||||
|
||||
mod blob_b64 {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&STANDARD.encode(bytes))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
STANDARD.decode(&s).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "ente-bus"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
serde = { workspace = true }
|
||||
postcard = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
ente-echo = { path = "../ente-echo" }
|
||||
|
||||
[[example]]
|
||||
name = "busctl"
|
||||
path = "examples/busctl.rs"
|
||||
@@ -0,0 +1,52 @@
|
||||
//! busctl: cliente CLI para el bus interno del fractal.
|
||||
//!
|
||||
//! Uso:
|
||||
//! cargo run --example busctl -- list-entes
|
||||
//! cargo run --example busctl -- announce
|
||||
//! cargo run --example busctl -- power-off
|
||||
//!
|
||||
//! Si `ENTE_BUS_SOCK` no está en el entorno, cae al path dev por defecto.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest};
|
||||
use std::env;
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("list-entes");
|
||||
|
||||
let mut client = match BusClient::from_env().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => {
|
||||
let user = env::var("USER").unwrap_or_else(|_| "ente".into());
|
||||
let runtime = env::var("XDG_RUNTIME_DIR")
|
||||
.unwrap_or_else(|_| env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()));
|
||||
let path = format!("{runtime}/ente-bus-{user}.sock");
|
||||
eprintln!("ENTE_BUS_SOCK no definido, intentando {path}");
|
||||
BusClient::connect(&path).await?
|
||||
}
|
||||
};
|
||||
|
||||
let req = match cmd {
|
||||
"list-entes" => BusRequest::ListEntes,
|
||||
"announce" => BusRequest::Announce { capabilities: vec![] },
|
||||
"power-off" => BusRequest::PowerOff { interactive: false },
|
||||
"reboot" => BusRequest::Reboot { interactive: false },
|
||||
"suspend" => BusRequest::Suspend { interactive: false },
|
||||
"invoke-echo" => {
|
||||
let msg = args.get(2).map(|s| s.as_str()).unwrap_or("hola");
|
||||
BusRequest::Invoke {
|
||||
cap: ente_echo::echo_capability(),
|
||||
blob: msg.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("subcomando desconocido: {other}");
|
||||
eprintln!("válidos: list-entes, announce, power-off, reboot, suspend, invoke-echo <text>");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let resp = client.call(req).await?;
|
||||
println!("{resp:#?}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! ente-bus: bus de capacidades interno del fractal.
|
||||
//!
|
||||
//! Wire format: Unix SOCK_STREAM con framing length-prefijo (u32 BE) + payload
|
||||
//! postcard. Bidireccional pero por ahora request-response síncrono.
|
||||
//!
|
||||
//! Identidad: cada Ente hijo recibe `ENTE_BUS_SOCK` y `ENTE_ID` en su entorno.
|
||||
//! El cliente lee ambos vía `BusClient::from_env`.
|
||||
|
||||
use ente_card::Capability;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use std::str::FromStr;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::UnixStream;
|
||||
use ulid::Ulid;
|
||||
|
||||
pub const ENV_BUS_SOCK: &str = "ENTE_BUS_SOCK";
|
||||
pub const ENV_ENTE_ID: &str = "ENTE_ID";
|
||||
pub const MAX_FRAME: usize = 1 << 20; // 1 MiB — protección contra OOM
|
||||
|
||||
/// Interface UUID para decisiones de policy. Un Ente independiente
|
||||
/// (separado de polkit-compat) se anuncia como proveedor de
|
||||
/// `Capability::Endpoint { interface: POLKIT_DECISION_IFACE, version: 1 }`
|
||||
/// para arbitrar autorizaciones. Recibe blob:
|
||||
/// `pid_be | uid_be | action_id_utf8` → responde 1 byte: 1=allow, 0=deny.
|
||||
pub const POLKIT_DECISION_IFACE: ente_card::InterfaceId =
|
||||
ente_card::InterfaceId([0xb0; 16]);
|
||||
|
||||
/// Interface UUID auto-anunciado por compat-polkit. Diferente al de
|
||||
/// decisión para evitar recursión (polkit-compat invoca DECISION pero
|
||||
/// no es proveedor de DECISION; se anuncia como SERVICE).
|
||||
pub const POLKIT_SERVICE_IFACE: ente_card::InterfaceId =
|
||||
ente_card::InterfaceId([0xa4; 16]);
|
||||
|
||||
/// Credenciales del peer extraídas vía SO_PEERCRED al accept del bus.
|
||||
/// Imposibles de falsear desde el cliente — el kernel las inyecta.
|
||||
/// Definidas aquí (no en ente-zero) porque conceptualmente son atributo
|
||||
/// del protocolo del bus, no del init.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PeerCreds {
|
||||
pub pid: i32,
|
||||
pub uid: u32,
|
||||
pub gid: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BusMessage {
|
||||
pub from: Option<Ulid>,
|
||||
pub seq: u64,
|
||||
pub payload: BusPayload,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum BusPayload {
|
||||
Request(BusRequest),
|
||||
Response(BusResponse),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum BusRequest {
|
||||
/// Saludo. El Ente anuncia que está vivo y declara sus capacidades.
|
||||
/// El Init usa esto para saber que el child arrancó correctamente,
|
||||
/// independientemente de su exit code.
|
||||
Announce { capabilities: Vec<Capability> },
|
||||
|
||||
/// Listar Entes vivos. Útil para debugging y para Entes-supervisor.
|
||||
ListEntes,
|
||||
|
||||
/// Control de estado del fractal. Traducido desde D-Bus por compat-logind.
|
||||
PowerOff { interactive: bool },
|
||||
Reboot { interactive: bool },
|
||||
Suspend { interactive: bool },
|
||||
Hibernate { interactive: bool },
|
||||
|
||||
/// Invocación genérica de capacidad. `cap` debe estar provista por algún
|
||||
/// Ente del grafo; el blob es el argumento opaco que el proveedor parsea.
|
||||
Invoke { cap: Capability, blob: Vec<u8> },
|
||||
|
||||
/// Actualización dinámica del set de capacidades del Ente que llama.
|
||||
/// Sólo aplicable al `from_authenticated` — un Ente sólo puede modificar
|
||||
/// sus propias caps. La Card original (immutable) no se toca; la mutación
|
||||
/// va al `dynamic_provides` del Incarnated.
|
||||
UpdateCapabilities {
|
||||
adds: Vec<Capability>,
|
||||
removes: Vec<Capability>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum BusResponse {
|
||||
Ok,
|
||||
Error(String),
|
||||
Entes(Vec<EnteInfo>),
|
||||
Invoked { result: Vec<u8> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EnteInfo {
|
||||
pub id: Ulid,
|
||||
pub label: String,
|
||||
pub provides: Vec<Capability>,
|
||||
pub pid: Option<i32>,
|
||||
}
|
||||
|
||||
pub async fn write_frame<W: AsyncWriteExt + Unpin>(w: &mut W, msg: &BusMessage) -> anyhow::Result<()> {
|
||||
let bytes = postcard::to_stdvec(msg)?;
|
||||
if bytes.len() > MAX_FRAME {
|
||||
anyhow::bail!("frame too large: {} > {}", bytes.len(), MAX_FRAME);
|
||||
}
|
||||
w.write_u32(bytes.len() as u32).await?;
|
||||
w.write_all(&bytes).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn read_frame<R: AsyncReadExt + Unpin>(r: &mut R) -> anyhow::Result<BusMessage> {
|
||||
let len = r.read_u32().await? as usize;
|
||||
if len > MAX_FRAME {
|
||||
anyhow::bail!("frame oversize: {len}");
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
r.read_exact(&mut buf).await?;
|
||||
Ok(postcard::from_bytes(&buf)?)
|
||||
}
|
||||
|
||||
pub struct BusClient {
|
||||
stream: UnixStream,
|
||||
seq: u64,
|
||||
self_id: Option<Ulid>,
|
||||
}
|
||||
|
||||
/// Trait que un Ente proveedor implementa para servir invokes que el bus le
|
||||
/// forwarda. Sync por simplicidad — un handler async se cubre con
|
||||
/// `tokio::task::block_in_place` o un canal hacia un task externo.
|
||||
pub trait InvokeHandler {
|
||||
fn handle(&mut self, cap: ente_card::Capability, blob: Vec<u8>) -> BusResponse;
|
||||
}
|
||||
|
||||
/// Conexión long-lived para Entes que proveen capacidades. A diferencia de
|
||||
/// `BusClient` (request-response y desconecta), `BusServer`:
|
||||
/// 1. Anuncia su identidad al bus
|
||||
/// 2. Mantiene la conexión abierta
|
||||
/// 3. Atiende invokes forwardeados por el bus en bucle
|
||||
pub struct BusServer {
|
||||
stream: UnixStream,
|
||||
self_id: Ulid,
|
||||
}
|
||||
|
||||
impl BusServer {
|
||||
pub async fn from_env() -> anyhow::Result<Self> {
|
||||
let path = std::env::var(ENV_BUS_SOCK)
|
||||
.map_err(|_| anyhow::anyhow!("{} no definido", ENV_BUS_SOCK))?;
|
||||
let id_s = std::env::var(ENV_ENTE_ID)
|
||||
.map_err(|_| anyhow::anyhow!("{} no definido", ENV_ENTE_ID))?;
|
||||
let self_id = Ulid::from_str(&id_s)
|
||||
.map_err(|_| anyhow::anyhow!("{} no es un Ulid válido: {id_s}", ENV_ENTE_ID))?;
|
||||
let stream = UnixStream::connect(&path).await?;
|
||||
Ok(Self { stream, self_id })
|
||||
}
|
||||
|
||||
pub async fn announce(&mut self, capabilities: Vec<ente_card::Capability>) -> anyhow::Result<()> {
|
||||
let req = BusMessage {
|
||||
from: Some(self.self_id),
|
||||
seq: 1,
|
||||
payload: BusPayload::Request(BusRequest::Announce { capabilities }),
|
||||
};
|
||||
write_frame(&mut self.stream, &req).await?;
|
||||
let resp = read_frame(&mut self.stream).await?;
|
||||
match resp.payload {
|
||||
BusPayload::Response(BusResponse::Ok) => Ok(()),
|
||||
BusPayload::Response(other) => anyhow::bail!("Announce rechazado: {other:?}"),
|
||||
BusPayload::Request(_) => anyhow::bail!("expected Response, got Request"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bucle principal del proveedor. Atiende invokes hasta que la conexión
|
||||
/// se cierra (el bus muere o el Ente recibe SIGTERM y nosotros dropeamos).
|
||||
pub async fn serve<H: InvokeHandler>(mut self, mut handler: H) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let msg = read_frame(&mut self.stream).await?;
|
||||
let resp = match msg.payload {
|
||||
BusPayload::Request(BusRequest::Invoke { cap, blob }) => {
|
||||
handler.handle(cap, blob)
|
||||
}
|
||||
BusPayload::Request(other) => {
|
||||
BusResponse::Error(format!("BusServer no maneja {other:?}"))
|
||||
}
|
||||
BusPayload::Response(_) => continue,
|
||||
};
|
||||
let out = BusMessage {
|
||||
from: Some(self.self_id),
|
||||
seq: msg.seq,
|
||||
payload: BusPayload::Response(resp),
|
||||
};
|
||||
write_frame(&mut self.stream, &out).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BusClient {
|
||||
pub async fn connect(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||
let stream = UnixStream::connect(path).await?;
|
||||
let self_id = std::env::var(ENV_ENTE_ID)
|
||||
.ok()
|
||||
.and_then(|s| Ulid::from_str(&s).ok());
|
||||
Ok(Self { stream, seq: 0, self_id })
|
||||
}
|
||||
|
||||
pub async fn from_env() -> anyhow::Result<Self> {
|
||||
let path = std::env::var(ENV_BUS_SOCK)
|
||||
.map_err(|_| anyhow::anyhow!("{} no definido", ENV_BUS_SOCK))?;
|
||||
Self::connect(&path).await
|
||||
}
|
||||
|
||||
pub async fn call(&mut self, req: BusRequest) -> anyhow::Result<BusResponse> {
|
||||
self.seq = self.seq.wrapping_add(1);
|
||||
let msg = BusMessage {
|
||||
from: self.self_id,
|
||||
seq: self.seq,
|
||||
payload: BusPayload::Request(req),
|
||||
};
|
||||
write_frame(&mut self.stream, &msg).await?;
|
||||
let resp = read_frame(&mut self.stream).await?;
|
||||
match resp.payload {
|
||||
BusPayload::Response(r) => Ok(r),
|
||||
BusPayload::Request(_) => anyhow::bail!("expected response, got request"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "ente-card"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
@@ -0,0 +1,178 @@
|
||||
# ============================================================================
|
||||
# card.k — REFERENCE ONLY. NOT LOADED.
|
||||
#
|
||||
# La validación canónica de EntityCard vive en Rust:
|
||||
# crates/ente-card/src/lib.rs :: EntityCard::validate()
|
||||
# El loader (crates/ente-brain/src/loader.rs) sólo acepta JSON.
|
||||
#
|
||||
# Este archivo se conserva como notas de diseño legibles para humanos sobre
|
||||
# las invariantes que `validate()` debe garantizar. Si modificas el shape
|
||||
# en Rust, sincroniza este archivo a mano (o reemplázalo por JSON Schema
|
||||
# generado vía `schemars`).
|
||||
# ============================================================================
|
||||
|
||||
# ---------- Identidad ----------
|
||||
|
||||
schema EntityCard:
|
||||
"""Tarjeta de Identidad. Inmutable: cambios = nueva Card con nuevo id."""
|
||||
schema_version: int = 1
|
||||
id: str # Ulid (26 chars, Crockford base32)
|
||||
lineage?: str # parent Ulid; None = Ente raíz
|
||||
label: str # legible, no es identificador
|
||||
provides: [Capability] = [] # contrato hacia el grafo
|
||||
requires: [Capability] = [] # contrato del grafo hacia el Ente
|
||||
soma: SomaSpec # cuerpo: aislamiento + recursos
|
||||
payload: Payload # cómo encarnar (Wasm/Native/Virtual)
|
||||
supervision: Supervision # política tras muerte
|
||||
genesis?: [EntityCard] = [] # hijos a instanciar al encarnar
|
||||
|
||||
check:
|
||||
schema_version == 1, "schema version no soportada"
|
||||
len(label) > 0, "label vacío"
|
||||
len(id) == 26, "id debe ser Ulid (26 caracteres)"
|
||||
# Auto-dependencia: una capacidad no puede estar en requires y provides
|
||||
all c in requires { c not in provides }, "self-dependency: ${c}"
|
||||
|
||||
|
||||
# ---------- Capacidades (typed enum) ----------
|
||||
|
||||
# KCL no tiene sum types nativos; usamos tagged union: `kind` + campos opcionales
|
||||
# que sólo aplican según el kind. Las invariantes en `check:` aseguran consistencia.
|
||||
schema Capability:
|
||||
"""Capacidad tipada del fractal. NUNCA usar strings libres."""
|
||||
kind: "FilesystemRoot" | "KernelNetlink" | "Endpoint" | "LegacyLogind" | "Device" | "Spawn" | "Journal"
|
||||
netlink_family?: "Uevent" | "Route" | "Generic" | "Audit"
|
||||
endpoint_interface?: str # 32-char hex (UUID 16 bytes)
|
||||
endpoint_version?: int
|
||||
device_class?: "Block" | "Tty" | "Input" | "Drm" | "Net" | "Hidraw"
|
||||
|
||||
check:
|
||||
kind != "KernelNetlink" or netlink_family is not None, \
|
||||
"KernelNetlink requiere netlink_family"
|
||||
kind != "Endpoint" or (endpoint_interface is not None and endpoint_version is not None), \
|
||||
"Endpoint requiere interface + version"
|
||||
kind != "Endpoint" or len(endpoint_interface) == 32, \
|
||||
"endpoint_interface debe ser hex de 32 chars"
|
||||
kind != "Device" or device_class is not None, \
|
||||
"Device requiere device_class"
|
||||
|
||||
|
||||
# ---------- Soma: cuerpo + restricciones de recursos ----------
|
||||
|
||||
schema SomaSpec:
|
||||
"""Aislamiento + recursos. Validados por KCL antes de tocar el kernel."""
|
||||
namespaces: NamespaceSet = NamespaceSet {}
|
||||
rlimits: ResourceLimits = ResourceLimits {}
|
||||
cgroup: CgroupSpec = CgroupSpec {}
|
||||
cpu_affinity?: [int] # CPU pinning
|
||||
|
||||
check:
|
||||
cpu_affinity is None or all c in cpu_affinity { c >= 0 and c < 1024 }, \
|
||||
"cpu_affinity fuera de rango [0, 1024)"
|
||||
|
||||
|
||||
schema NamespaceSet:
|
||||
mount: bool = False
|
||||
pid: bool = False
|
||||
net: bool = False
|
||||
uts: bool = False
|
||||
ipc: bool = False
|
||||
user: bool = False
|
||||
cgroup: bool = False
|
||||
|
||||
|
||||
schema ResourceLimits:
|
||||
"""Restricciones nativas validadas en KCL — el kernel sólo ve valores sanos."""
|
||||
mem_bytes?: int # RLIMIT_AS
|
||||
nproc?: int # RLIMIT_NPROC
|
||||
nofile?: int # RLIMIT_NOFILE
|
||||
energy_budget_mw?: int # presupuesto energético (futuro)
|
||||
|
||||
check:
|
||||
mem_bytes is None or mem_bytes > 0, "mem_bytes debe ser positivo"
|
||||
mem_bytes is None or mem_bytes <= 1099511627776, "mem_bytes > 1 TiB sospechoso"
|
||||
nproc is None or (nproc > 0 and nproc <= 65535), "nproc fuera de rango"
|
||||
nofile is None or (nofile > 0 and nofile <= 1048576), "nofile fuera de rango"
|
||||
energy_budget_mw is None or energy_budget_mw > 0, "energy_budget_mw debe ser positivo"
|
||||
|
||||
|
||||
schema CgroupSpec:
|
||||
"""Cgroup v2: path + weights. cpu_weight 1..10000 según kernel docs."""
|
||||
path: str = ""
|
||||
cpu_weight?: int
|
||||
io_weight?: int
|
||||
|
||||
check:
|
||||
cpu_weight is None or (cpu_weight >= 1 and cpu_weight <= 10000), \
|
||||
"cpu_weight 1..10000"
|
||||
io_weight is None or (io_weight >= 1 and io_weight <= 10000), \
|
||||
"io_weight 1..10000"
|
||||
|
||||
|
||||
# ---------- Payload: tagged union de cómo encarnar ----------
|
||||
|
||||
schema Payload:
|
||||
"""Una variante por Card. Set exactly one of: Wasm, Native, Virtual, Legacy."""
|
||||
kind: "Wasm" | "Native" | "Virtual" | "Legacy"
|
||||
# Wasm
|
||||
module_sha256?: str # hex 64 chars
|
||||
entry?: str
|
||||
# Native / Legacy
|
||||
exec?: str
|
||||
argv?: [str] = []
|
||||
envp?: [{str: str}] = []
|
||||
# Legacy
|
||||
fakes?: ["SystemdLogind" | "SystemdHostnamed" | "SystemdNotify"] = []
|
||||
|
||||
check:
|
||||
kind != "Wasm" or (module_sha256 is not None and entry is not None), \
|
||||
"Wasm requiere module_sha256 + entry"
|
||||
kind != "Wasm" or len(module_sha256) == 64, "module_sha256 debe ser hex de 64 chars"
|
||||
kind != "Native" or exec is not None, "Native requiere exec"
|
||||
kind != "Legacy" or exec is not None, "Legacy requiere exec"
|
||||
|
||||
|
||||
# ---------- Supervision ----------
|
||||
|
||||
schema Supervision:
|
||||
kind: "Restart" | "OneShot" | "Delegate"
|
||||
initial_ms?: int # ms — backoff inicial para Restart
|
||||
max_ms?: int # ms — backoff máximo
|
||||
|
||||
check:
|
||||
kind != "Restart" or (initial_ms is not None and max_ms is not None), \
|
||||
"Restart requiere initial_ms + max_ms"
|
||||
initial_ms is None or initial_ms >= 0, "initial_ms negativo"
|
||||
max_ms is None or max_ms >= initial_ms or max_ms is None, \
|
||||
"max_ms < initial_ms es contradictorio"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Herencia: EnteWeb hereda de EnteBase con campos pre-rellenados.
|
||||
# ============================================================================
|
||||
|
||||
schema EnteBase(EntityCard):
|
||||
"""Base para Entes managed: declara Spawn provider y Journal por defecto."""
|
||||
schema_version = 1
|
||||
supervision = Supervision {kind = "Restart", initial_ms = 100, max_ms = 30000}
|
||||
soma = SomaSpec {
|
||||
rlimits = ResourceLimits {nofile = 4096}
|
||||
cgroup = CgroupSpec {path = "ente.slice/managed", cpu_weight = 100}
|
||||
}
|
||||
|
||||
|
||||
schema EnteWeb(EnteBase):
|
||||
"""Hereda EnteBase, declara endpoint + cap LegacyLogind como ejemplo."""
|
||||
provides = [
|
||||
Capability {kind = "Journal"}
|
||||
Capability {
|
||||
kind = "Endpoint"
|
||||
endpoint_interface = "deadbeefcafe1234deadbeefcafe1234"
|
||||
endpoint_version = 1
|
||||
}
|
||||
]
|
||||
soma = SomaSpec {
|
||||
namespaces = NamespaceSet {net = True, mount = True, pid = True}
|
||||
rlimits = ResourceLimits {nofile = 16384, mem_bytes = 536870912} # 512 MiB
|
||||
cgroup = CgroupSpec {path = "ente.slice/web", cpu_weight = 200, io_weight = 100}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
//! ente-card: definición de la Tarjeta de Identidad del Ente.
|
||||
//!
|
||||
//! Una `EntityCard` no describe un proceso — describe una identidad en el
|
||||
//! grafo del fractal. El Init la lee y decide cómo *encarnarla*: como ELF
|
||||
//! nativo, módulo Wasm, wrapper legacy, o nodo virtual sin proceso.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
use std::time::Duration;
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Versión del esquema de la Card. Cambiar = romper compatibilidad del fractal.
|
||||
pub const CARD_SCHEMA_VERSION: u16 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EntityCard {
|
||||
pub schema_version: u16,
|
||||
pub id: Ulid,
|
||||
pub lineage: Option<Ulid>,
|
||||
pub label: String,
|
||||
pub provides: BTreeSet<Capability>,
|
||||
pub requires: BTreeSet<Capability>,
|
||||
pub soma: SomaSpec,
|
||||
pub payload: Payload,
|
||||
pub supervision: Supervision,
|
||||
/// Hijos a instanciar inmediatamente cuando esta Card se encarna. Se
|
||||
/// consumen una vez (no se replican en restarts del padre — el grafo
|
||||
/// re-emerge desde la Semilla viva, no desde la persistencia de la Card).
|
||||
#[serde(default)]
|
||||
pub genesis: Vec<EntityCard>,
|
||||
}
|
||||
|
||||
impl EntityCard {
|
||||
pub fn validate(&self) -> Result<(), CardError> {
|
||||
if self.schema_version != CARD_SCHEMA_VERSION {
|
||||
return Err(CardError::SchemaMismatch {
|
||||
got: self.schema_version,
|
||||
expected: CARD_SCHEMA_VERSION,
|
||||
});
|
||||
}
|
||||
if self.label.is_empty() {
|
||||
return Err(CardError::EmptyLabel);
|
||||
}
|
||||
if self.label.len() > 256 {
|
||||
return Err(CardError::LabelTooLong(self.label.len()));
|
||||
}
|
||||
// Una capacidad simultáneamente en `requires` y `provides` indica un
|
||||
// ciclo de auto-dependencia que el grafo no puede resolver.
|
||||
for cap in &self.requires {
|
||||
if self.provides.contains(cap) {
|
||||
return Err(CardError::SelfDependency(cap.clone()));
|
||||
}
|
||||
}
|
||||
// Coherencia del payload con sus invariantes.
|
||||
validate_payload(&self.payload)?;
|
||||
// ResourceLimits: rangos sanos.
|
||||
validate_rlimits(&self.soma.rlimits)?;
|
||||
// Cgroup weights: 1..10000 según docs del kernel cgroup v2.
|
||||
validate_cgroup(&self.soma.cgroup)?;
|
||||
// Validación recursiva de genesis. Si una hija es inválida, la
|
||||
// Semilla entera se rechaza — falla rápida en boot.
|
||||
for child in &self.genesis {
|
||||
child.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CardError {
|
||||
SchemaMismatch { got: u16, expected: u16 },
|
||||
EmptyLabel,
|
||||
LabelTooLong(usize),
|
||||
SelfDependency(Capability),
|
||||
EmptyExec,
|
||||
SentinelWasmHash,
|
||||
InvalidRlimit(&'static str),
|
||||
InvalidCgroupWeight(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for CardError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::SchemaMismatch { got, expected } => {
|
||||
write!(f, "schema version mismatch: got {got}, expected {expected}")
|
||||
}
|
||||
Self::EmptyLabel => write!(f, "card label is empty"),
|
||||
Self::LabelTooLong(n) => write!(f, "label demasiado largo ({n} bytes, max 256)"),
|
||||
Self::SelfDependency(c) => write!(f, "card both requires and provides {c:?}"),
|
||||
Self::EmptyExec => write!(f, "Native/Legacy payload con exec vacío"),
|
||||
Self::SentinelWasmHash => write!(f, "Wasm payload con sha256 sentinel (todo ceros)"),
|
||||
Self::InvalidRlimit(s) => write!(f, "rlimit inválido: {s}"),
|
||||
Self::InvalidCgroupWeight(s) => write!(f, "cgroup weight fuera de rango [1,10000]: {s}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CardError {}
|
||||
|
||||
fn validate_payload(p: &Payload) -> Result<(), CardError> {
|
||||
match p {
|
||||
Payload::Native { exec, .. } | Payload::Legacy { exec, .. } => {
|
||||
if exec.trim().is_empty() {
|
||||
return Err(CardError::EmptyExec);
|
||||
}
|
||||
}
|
||||
Payload::Wasm { module_sha256, .. } => {
|
||||
// Sentinel [0u8; 32] indica "no resoluble" — usado en dev como
|
||||
// fallback. En prod debe ser un hash real.
|
||||
if module_sha256.iter().all(|&b| b == 0) {
|
||||
return Err(CardError::SentinelWasmHash);
|
||||
}
|
||||
}
|
||||
Payload::Virtual => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_rlimits(rl: &ResourceLimits) -> Result<(), CardError> {
|
||||
if let Some(m) = rl.mem_bytes {
|
||||
if m == 0 { return Err(CardError::InvalidRlimit("mem_bytes=0")); }
|
||||
if m > 1u64 << 40 { return Err(CardError::InvalidRlimit("mem_bytes>1TiB")); }
|
||||
}
|
||||
if let Some(n) = rl.nproc {
|
||||
if n == 0 || n > 65535 { return Err(CardError::InvalidRlimit("nproc fuera de [1,65535]")); }
|
||||
}
|
||||
if let Some(n) = rl.nofile {
|
||||
if n == 0 || n > 1_048_576 { return Err(CardError::InvalidRlimit("nofile fuera de [1,1M]")); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_cgroup(cg: &CgroupSpec) -> Result<(), CardError> {
|
||||
if let Some(w) = cg.cpu_weight {
|
||||
if !(1..=10000).contains(&w) { return Err(CardError::InvalidCgroupWeight("cpu_weight")); }
|
||||
}
|
||||
if let Some(w) = cg.io_weight {
|
||||
if !(1..=10000).contains(&w) { return Err(CardError::InvalidCgroupWeight("io_weight")); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Capability {
|
||||
/// Provee un punto de montaje root para Entes hijos.
|
||||
FilesystemRoot,
|
||||
/// Acceso a una familia de netlink.
|
||||
KernelNetlink(NetlinkFamily),
|
||||
/// Endpoint del bus interno del fractal — equivalente tipado de un nombre
|
||||
/// D-Bus, sin la string libre.
|
||||
Endpoint { interface: InterfaceId, version: u16 },
|
||||
/// Reemplazo del shim de systemd-logind. Solo Ente #compat-logind lo provee.
|
||||
LegacyLogind,
|
||||
/// Acceso crudo a una clase de dispositivo. Capacidad escalada.
|
||||
Device { class: DeviceClass },
|
||||
/// Permiso de instanciar Entes hijos. Por defecto solo PID 1 lo tiene.
|
||||
Spawn,
|
||||
/// Acceso a logging estructurado del fractal.
|
||||
Journal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum NetlinkFamily { Uevent, Route, Generic, Audit }
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum DeviceClass { Block, Tty, Input, Drm, Net, Hidraw }
|
||||
|
||||
/// Identificador de interfaz del bus interno. UUID, no string. Para extender
|
||||
/// el protocolo del fractal, generas un UUID nuevo y versionas.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct InterfaceId(pub [u8; 16]);
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct SomaSpec {
|
||||
pub namespaces: NamespaceSet,
|
||||
pub rlimits: ResourceLimits,
|
||||
pub cgroup: CgroupSpec,
|
||||
pub cpu_affinity: Option<Vec<u32>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct NamespaceSet {
|
||||
pub mount: bool,
|
||||
pub pid: bool,
|
||||
pub net: bool,
|
||||
pub uts: bool,
|
||||
pub ipc: bool,
|
||||
pub user: bool,
|
||||
pub cgroup: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct ResourceLimits {
|
||||
pub mem_bytes: Option<u64>,
|
||||
pub nproc: Option<u32>,
|
||||
pub nofile: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct CgroupSpec {
|
||||
pub path: String,
|
||||
pub cpu_weight: Option<u32>,
|
||||
pub io_weight: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum Payload {
|
||||
Wasm { module_sha256: [u8; 32], entry: String },
|
||||
Native {
|
||||
exec: String,
|
||||
argv: Vec<String>,
|
||||
envp: Vec<(String, String)>,
|
||||
},
|
||||
/// Sin proceso. Nodo lógico del grafo (agregadores, mediators).
|
||||
Virtual,
|
||||
/// Wrapper de daemon legacy. `fakes` activa shims D-Bus / sd_notify.
|
||||
Legacy {
|
||||
exec: String,
|
||||
argv: Vec<String>,
|
||||
fakes: BTreeSet<LegacyFacade>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum LegacyFacade {
|
||||
SystemdLogind,
|
||||
SystemdHostnamed,
|
||||
SystemdNotify,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum Supervision {
|
||||
Restart {
|
||||
#[serde(with = "duration_millis")]
|
||||
initial: Duration,
|
||||
#[serde(with = "duration_millis")]
|
||||
max: Duration,
|
||||
},
|
||||
OneShot,
|
||||
Delegate,
|
||||
}
|
||||
|
||||
mod duration_millis {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn serialize<S: Serializer>(d: &Duration, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_u64(d.as_millis() as u64)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
|
||||
let ms = u64::deserialize(d)?;
|
||||
Ok(Duration::from_millis(ms))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn seed_card_validates() {
|
||||
let card = EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: "ente-zero".into(),
|
||||
provides: [Capability::Spawn, Capability::Journal].into_iter().collect(),
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec::default(),
|
||||
payload: Payload::Virtual,
|
||||
supervision: Supervision::OneShot,
|
||||
genesis: vec![],
|
||||
};
|
||||
card.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_dependency_rejected() {
|
||||
let mut s = BTreeSet::new();
|
||||
s.insert(Capability::Journal);
|
||||
let card = EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: "bad".into(),
|
||||
provides: s.clone(),
|
||||
requires: s,
|
||||
soma: SomaSpec::default(),
|
||||
payload: Payload::Virtual,
|
||||
supervision: Supervision::OneShot,
|
||||
genesis: vec![],
|
||||
};
|
||||
assert!(matches!(card.validate(), Err(CardError::SelfDependency(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_genesis_propagates() {
|
||||
let bad_child = EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: "".into(),
|
||||
provides: BTreeSet::new(),
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec::default(),
|
||||
payload: Payload::Virtual,
|
||||
supervision: Supervision::OneShot,
|
||||
genesis: vec![],
|
||||
};
|
||||
let parent = EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: "parent".into(),
|
||||
provides: BTreeSet::new(),
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec::default(),
|
||||
payload: Payload::Virtual,
|
||||
supervision: Supervision::OneShot,
|
||||
genesis: vec![bad_child],
|
||||
};
|
||||
assert!(matches!(parent.validate(), Err(CardError::EmptyLabel)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "ente-cas"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sha2 = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Content-addressable store. Resuelve `Payload::Wasm.module_sha256` (y en
|
||||
//! el futuro otros payloads firmados) desde el sistema de archivos con
|
||||
//! verificación de hash. Path por defecto: `$XDG_DATA_HOME/ente/cas/<hex>`.
|
||||
//!
|
||||
//! Override por env: `ENTE_CAS_ROOT`.
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::PathBuf;
|
||||
use tracing::debug;
|
||||
|
||||
pub fn cas_root() -> PathBuf {
|
||||
if let Ok(p) = std::env::var("ENTE_CAS_ROOT") {
|
||||
return p.into();
|
||||
}
|
||||
let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") {
|
||||
d
|
||||
} else if let Ok(h) = std::env::var("HOME") {
|
||||
format!("{h}/.local/share")
|
||||
} else {
|
||||
"/var/lib".into()
|
||||
};
|
||||
PathBuf::from(base).join("ente").join("cas")
|
||||
}
|
||||
|
||||
pub fn sha256_of(bytes: &[u8]) -> [u8; 32] {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(bytes);
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
pub fn hex(sha: &[u8; 32]) -> String {
|
||||
let mut s = String::with_capacity(64);
|
||||
for b in sha {
|
||||
s.push_str(&format!("{:02x}", b));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Lista todos los SHAs presentes en el CAS. Cada entrada del directorio
|
||||
/// con nombre de 64 chars hex se considera un blob válido.
|
||||
pub fn list_all_shas() -> anyhow::Result<Vec<[u8; 32]>> {
|
||||
let root = cas_root();
|
||||
if !root.exists() { return Ok(Vec::new()); }
|
||||
let mut out = Vec::new();
|
||||
for entry in std::fs::read_dir(&root)? {
|
||||
let e = entry?;
|
||||
let name = e.file_name();
|
||||
let s = match name.to_str() {
|
||||
Some(s) if s.len() == 64 => s,
|
||||
_ => continue,
|
||||
};
|
||||
let mut sha = [0u8; 32];
|
||||
let mut ok = true;
|
||||
for i in 0..32 {
|
||||
match u8::from_str_radix(&s[i*2..i*2+2], 16) {
|
||||
Ok(b) => sha[i] = b,
|
||||
Err(_) => { ok = false; break; }
|
||||
}
|
||||
}
|
||||
if ok { out.push(sha); }
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Garbage collector. Borra todos los blobs que no están en `reachable`.
|
||||
/// Devuelve (deleted_count, freed_bytes). El caller construye `reachable`
|
||||
/// caminando todas las raíces (audit chain head, Wasm SHAs en Cards, etc).
|
||||
///
|
||||
/// Idempotente: re-correr no hace nada si el set no cambió.
|
||||
pub fn gc(reachable: &std::collections::HashSet<[u8; 32]>) -> anyhow::Result<(usize, u64)> {
|
||||
let root = cas_root();
|
||||
let mut deleted = 0usize;
|
||||
let mut freed = 0u64;
|
||||
for sha in list_all_shas()? {
|
||||
if reachable.contains(&sha) { continue; }
|
||||
let path = root.join(hex(&sha));
|
||||
if let Ok(meta) = std::fs::metadata(&path) {
|
||||
freed += meta.len();
|
||||
}
|
||||
if std::fs::remove_file(&path).is_ok() {
|
||||
deleted += 1;
|
||||
tracing::debug!(sha = %hex(&sha), "CAS gc removed");
|
||||
}
|
||||
}
|
||||
Ok((deleted, freed))
|
||||
}
|
||||
|
||||
pub fn resolve(sha: &[u8; 32]) -> anyhow::Result<Vec<u8>> {
|
||||
let path = cas_root().join(hex(sha));
|
||||
let bytes = std::fs::read(&path)
|
||||
.map_err(|e| anyhow::anyhow!("CAS read {}: {e}", path.display()))?;
|
||||
let actual = sha256_of(&bytes);
|
||||
if &actual != sha {
|
||||
anyhow::bail!(
|
||||
"CAS hash mismatch en {}: declarado={} real={}",
|
||||
path.display(), hex(sha), hex(&actual)
|
||||
);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Almacena bytes en el CAS, devuelve su SHA. Idempotente: si el archivo ya
|
||||
/// existe con el mismo hash, no reescribe.
|
||||
pub fn store(bytes: &[u8]) -> anyhow::Result<[u8; 32]> {
|
||||
let sha = sha256_of(bytes);
|
||||
let root = cas_root();
|
||||
std::fs::create_dir_all(&root)
|
||||
.map_err(|e| anyhow::anyhow!("CAS mkdir {}: {e}", root.display()))?;
|
||||
let path = root.join(hex(&sha));
|
||||
if !path.exists() {
|
||||
// Escritura atómica: crear .tmp y rename.
|
||||
let tmp = path.with_extension("tmp");
|
||||
std::fs::write(&tmp, bytes)
|
||||
.map_err(|e| anyhow::anyhow!("CAS write {}: {e}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, &path)
|
||||
.map_err(|e| anyhow::anyhow!("CAS rename {}: {e}", path.display()))?;
|
||||
debug!(hex = %hex(&sha), len = bytes.len(), path = %path.display(), "CAS store");
|
||||
}
|
||||
Ok(sha)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "ente-echo"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "ente_echo"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ente-echo"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Constantes públicas del Ente echo. Lib aparte del bin para que `busctl`
|
||||
//! y otros consumidores puedan importar el InterfaceId sin enlazar el binario.
|
||||
|
||||
use ente_card::{Capability, InterfaceId};
|
||||
|
||||
/// UUID estable del interface "echo". Genera nuevo por sed si forkeas.
|
||||
pub const ECHO_IFACE: InterfaceId = InterfaceId([
|
||||
0xec, 0x40, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x01,
|
||||
0x80, 0x00, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe,
|
||||
]);
|
||||
pub const ECHO_VERSION: u16 = 1;
|
||||
|
||||
pub fn echo_capability() -> Capability {
|
||||
Capability::Endpoint {
|
||||
interface: ECHO_IFACE,
|
||||
version: ECHO_VERSION,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! ente-echo: Ente proveedor mínimo. Anuncia Capability::Endpoint(ECHO) y
|
||||
//! responde a invokes echando el blob recibido. Vehículo para validar el
|
||||
//! forwarding bus → proveedor → bus → originator.
|
||||
|
||||
use ente_bus::{BusResponse, BusServer, InvokeHandler};
|
||||
use ente_card::Capability;
|
||||
use ente_echo::{echo_capability, ECHO_IFACE, ECHO_VERSION};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
struct EchoHandler;
|
||||
|
||||
impl InvokeHandler for EchoHandler {
|
||||
fn handle(&mut self, cap: Capability, blob: Vec<u8>) -> BusResponse {
|
||||
match cap {
|
||||
Capability::Endpoint { interface, version }
|
||||
if interface == ECHO_IFACE && version == ECHO_VERSION =>
|
||||
{
|
||||
let preview = String::from_utf8_lossy(&blob).into_owned();
|
||||
info!(text = %preview, len = blob.len(), "echo invoke");
|
||||
BusResponse::Invoked { result: blob }
|
||||
}
|
||||
other => {
|
||||
warn!(?other, "ente-echo: capacidad no soportada");
|
||||
BusResponse::Error("ente-echo solo maneja ECHO_IFACE".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_echo=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
|
||||
info!("ente-echo arrancando");
|
||||
let mut server = BusServer::from_env().await?;
|
||||
server.announce(vec![echo_capability()]).await?;
|
||||
info!("Announce OK, sirviendo invokes");
|
||||
|
||||
if let Err(e) = server.serve(EchoHandler).await {
|
||||
warn!(?e, "serve terminó");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "ente-hostnamed-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-hostnamed-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,340 @@
|
||||
//! ente-hostnamed-compat: shim de `org.freedesktop.hostname1`.
|
||||
//!
|
||||
//! GNOME control-center y otros componentes consultan este servicio al boot
|
||||
//! para mostrar nombre de host, OS, kernel. Sin esto los settings panels
|
||||
//! se rompen aunque el sistema funcione.
|
||||
//!
|
||||
//! Read-only properties: leemos /etc/hostname, /etc/os-release, uname().
|
||||
//! Set* methods: log + forward al bus interno (no aplicamos cambios reales
|
||||
//! en el stub — un siguiente paso es persistir a /etc/* y rehash).
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::sync::Mutex;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface, Connection};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.hostname1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/hostname1";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-hostnamed-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = HostnameManager::default();
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "build conn falló — modo idle");
|
||||
wait_for_term().await
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
warn!(?e, "builder D-Bus falló — modo idle");
|
||||
wait_for_term().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct HostnameManager {
|
||||
/// Cache para SetHostname. En el stub no persistimos a /etc.
|
||||
transient_hostname: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
#[interface(name = "org.freedesktop.hostname1")]
|
||||
impl HostnameManager {
|
||||
// ----- Properties read-only -----
|
||||
|
||||
#[zbus(property)]
|
||||
async fn hostname(&self) -> String {
|
||||
if let Some(h) = self.transient_hostname.lock().unwrap().clone() {
|
||||
return h;
|
||||
}
|
||||
gethostname_libc().unwrap_or_else(|| "localhost".into())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn static_hostname(&self) -> String {
|
||||
std::fs::read_to_string("/etc/hostname")
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn pretty_hostname(&self) -> String {
|
||||
read_machine_info_field("PRETTY_HOSTNAME").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn icon_name(&self) -> String {
|
||||
read_machine_info_field("ICON_NAME").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn chassis(&self) -> String {
|
||||
read_machine_info_field("CHASSIS").unwrap_or_else(|| "desktop".into())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn deployment(&self) -> String {
|
||||
read_machine_info_field("DEPLOYMENT").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn location(&self) -> String {
|
||||
read_machine_info_field("LOCATION").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn kernel_name(&self) -> String {
|
||||
nix::sys::utsname::uname()
|
||||
.ok()
|
||||
.and_then(|u| u.sysname().to_str().map(String::from))
|
||||
.unwrap_or_else(|| "Linux".into())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn kernel_release(&self) -> String {
|
||||
nix::sys::utsname::uname()
|
||||
.ok()
|
||||
.and_then(|u| u.release().to_str().map(String::from))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn kernel_version(&self) -> String {
|
||||
nix::sys::utsname::uname()
|
||||
.ok()
|
||||
.and_then(|u| u.version().to_str().map(String::from))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn operating_system_pretty_name(&self) -> String {
|
||||
read_os_release_field("PRETTY_NAME").unwrap_or_else(|| "Linux".into())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn operating_system_cpename(&self) -> String {
|
||||
read_os_release_field("CPE_NAME").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn home_url(&self) -> String {
|
||||
read_os_release_field("HOME_URL").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn hardware_vendor(&self) -> String {
|
||||
read_dmi("/sys/class/dmi/id/sys_vendor")
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn hardware_model(&self) -> String {
|
||||
read_dmi("/sys/class/dmi/id/product_name")
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn firmware_version(&self) -> String {
|
||||
read_dmi("/sys/class/dmi/id/bios_version")
|
||||
}
|
||||
|
||||
// ----- Setters: forward al bus interno y guardan en cache -----
|
||||
|
||||
async fn set_hostname(&self, name: String, _interactive: bool) -> fdo::Result<()> {
|
||||
if !is_valid_hostname(&name) {
|
||||
return Err(fdo::Error::InvalidArgs(format!("hostname inválido: {name:?}")));
|
||||
}
|
||||
// sethostname(2) cambia sólo el running kernel value.
|
||||
let cstr = std::ffi::CString::new(name.clone())
|
||||
.map_err(|e| fdo::Error::Failed(format!("CString: {e}")))?;
|
||||
let r = unsafe { libc::sethostname(cstr.as_ptr(), name.len()) };
|
||||
if r != 0 {
|
||||
warn!(error = %std::io::Error::last_os_error(), %name, "sethostname syscall falló (¿CAP_SYS_ADMIN?)");
|
||||
// No es fatal — guardamos transient para que el property lea el valor nuevo.
|
||||
}
|
||||
*self.transient_hostname.lock().unwrap() = Some(name.clone());
|
||||
info!(%name, "SetHostname aplicado");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_static_hostname(&self, name: String, _interactive: bool) -> fdo::Result<()> {
|
||||
if !is_valid_hostname(&name) {
|
||||
return Err(fdo::Error::InvalidArgs(format!("hostname inválido: {name:?}")));
|
||||
}
|
||||
atomic_write("/etc/hostname", format!("{name}\n").as_bytes())
|
||||
.map_err(|e| fdo::Error::Failed(format!("write /etc/hostname: {e}")))?;
|
||||
info!(%name, "SetStaticHostname → /etc/hostname");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_pretty_hostname(&self, name: String, _interactive: bool) -> fdo::Result<()> {
|
||||
update_machine_info("PRETTY_HOSTNAME", &name)
|
||||
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
|
||||
info!(%name, "SetPrettyHostname → /etc/machine-info");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_icon_name(&self, name: String, _interactive: bool) -> fdo::Result<()> {
|
||||
update_machine_info("ICON_NAME", &name)
|
||||
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
|
||||
info!(%name, "SetIconName → /etc/machine-info");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_chassis(&self, chassis: String, _interactive: bool) -> fdo::Result<()> {
|
||||
if !matches!(chassis.as_str(), "desktop"|"laptop"|"server"|"tablet"|"handset"|"watch"|"embedded"|"vm"|"container") {
|
||||
return Err(fdo::Error::InvalidArgs(format!("chassis inválido: {chassis}")));
|
||||
}
|
||||
update_machine_info("CHASSIS", &chassis)
|
||||
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
|
||||
info!(%chassis, "SetChassis → /etc/machine-info");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_deployment(&self, deployment: String, _interactive: bool) -> fdo::Result<()> {
|
||||
update_machine_info("DEPLOYMENT", &deployment)
|
||||
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
|
||||
info!(%deployment, "SetDeployment → /etc/machine-info");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_location(&self, location: String, _interactive: bool) -> fdo::Result<()> {
|
||||
update_machine_info("LOCATION", &location)
|
||||
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
|
||||
info!(%location, "SetLocation → /etc/machine-info");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- helpers ----------------
|
||||
|
||||
fn gethostname_libc() -> Option<String> {
|
||||
let mut buf = [0u8; 256];
|
||||
let r = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut _, buf.len()) };
|
||||
if r != 0 { return None; }
|
||||
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
|
||||
std::str::from_utf8(&buf[..len]).ok().map(String::from)
|
||||
}
|
||||
|
||||
fn read_os_release_field(field: &str) -> Option<String> {
|
||||
parse_kv_file("/etc/os-release", field)
|
||||
}
|
||||
|
||||
fn read_machine_info_field(field: &str) -> Option<String> {
|
||||
parse_kv_file("/etc/machine-info", field)
|
||||
}
|
||||
|
||||
fn parse_kv_file(path: &str, field: &str) -> Option<String> {
|
||||
let content = std::fs::read_to_string(path).ok()?;
|
||||
for line in content.lines() {
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
if k.trim() == field {
|
||||
return Some(v.trim().trim_matches('"').to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_dmi(path: &str) -> String {
|
||||
std::fs::read_to_string(path)
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// RFC 1123 + extra: ASCII alfanumérico, dash, dot. Longitud 1..253.
|
||||
/// Rechaza vacíos, espacios, control chars.
|
||||
fn is_valid_hostname(s: &str) -> bool {
|
||||
if s.is_empty() || s.len() > 253 { return false; }
|
||||
s.chars().all(|c|
|
||||
c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_'
|
||||
)
|
||||
}
|
||||
|
||||
/// Escritura atómica via tmp + rename. fsync del directorio para
|
||||
/// garantizar durabilidad post-crash. Permisos 0644.
|
||||
fn atomic_write(path: &str, content: &[u8]) -> std::io::Result<()> {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let p = std::path::Path::new(path);
|
||||
if let Some(parent) = p.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
let tmp = p.with_extension("tmp");
|
||||
{
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.create(true).write(true).truncate(true)
|
||||
.mode(0o644)
|
||||
.open(&tmp)?;
|
||||
f.write_all(content)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, p)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lee /etc/machine-info, actualiza/inserta una clave, escribe atómico.
|
||||
fn update_machine_info(key: &str, value: &str) -> std::io::Result<()> {
|
||||
let path = "/etc/machine-info";
|
||||
let existing = std::fs::read_to_string(path).unwrap_or_default();
|
||||
let mut found = false;
|
||||
let mut out = String::new();
|
||||
for line in existing.lines() {
|
||||
if let Some((k, _)) = line.split_once('=') {
|
||||
if k.trim() == key {
|
||||
out.push_str(&format!("{key}={value}\n"));
|
||||
found = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
if !found {
|
||||
out.push_str(&format!("{key}={value}\n"));
|
||||
}
|
||||
atomic_write(path, out.as_bytes())
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa0; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_hostnamed_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "ente-journald-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-journald-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ente-journalctl"
|
||||
path = "src/journalctl.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
ente-cas = { path = "../ente-cas" }
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,289 @@
|
||||
//! ente-journalctl: query CLI sobre el journal persistido en CAS.
|
||||
//!
|
||||
//! Lee el index `~/.local/share/ente/journal/index.log` (líneas
|
||||
//! `timestamp_ms:source:unit:sha_hex`), filtra, y para cada match
|
||||
//! restituye el blob desde CAS y lo imprime.
|
||||
//!
|
||||
//! Uso:
|
||||
//! ente-journalctl # todo el journal
|
||||
//! ente-journalctl --unit foo.service # filtra por unit
|
||||
//! ente-journalctl --since 60 # últimos 60 segundos
|
||||
//! ente-journalctl --grep "panic" # contiene "panic"
|
||||
//! ente-journalctl --tail 20 # últimas 20 entries
|
||||
//! ente-journalctl --json # output JSON-lines
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
struct Args {
|
||||
unit: Option<String>,
|
||||
since_secs: Option<u64>,
|
||||
grep: Option<String>,
|
||||
tail: Option<usize>,
|
||||
source: Option<String>,
|
||||
output: OutputFormat,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum OutputFormat {
|
||||
Pretty,
|
||||
Json,
|
||||
/// systemd journal export format: `KEY=value\n` por field, blank line
|
||||
/// entre entries. Documented at https://systemd.io/JOURNAL_EXPORT_FORMATS/
|
||||
/// Compatible con `journalctl --input-format=export`.
|
||||
Export,
|
||||
}
|
||||
|
||||
fn parse_args() -> Args {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mut a = Args {
|
||||
unit: None, since_secs: None, grep: None, tail: None,
|
||||
source: None, output: OutputFormat::Pretty,
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--unit" | "-u" => a.unit = args.next(),
|
||||
"--since" | "-S" => a.since_secs = args.next().and_then(|s| s.parse().ok()),
|
||||
"--grep" | "-g" => a.grep = args.next(),
|
||||
"--tail" | "-n" => a.tail = args.next().and_then(|s| s.parse().ok()),
|
||||
"--source" => a.source = args.next(),
|
||||
"--json" => a.output = OutputFormat::Json,
|
||||
"--output" | "-o" => {
|
||||
a.output = match args.next().as_deref() {
|
||||
Some("pretty") | None => OutputFormat::Pretty,
|
||||
Some("json") | Some("json-lines") => OutputFormat::Json,
|
||||
Some("export") => OutputFormat::Export,
|
||||
Some(other) => {
|
||||
eprintln!("output desconocido: {other}");
|
||||
eprintln!("válidos: pretty | json | export");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
}
|
||||
"-h" | "--help" => { print_help(); std::process::exit(0); }
|
||||
other => {
|
||||
eprintln!("argumento desconocido: {other}");
|
||||
print_help();
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn print_help() {
|
||||
eprintln!("ente-journalctl — query CLI del journal persistido en CAS");
|
||||
eprintln!();
|
||||
eprintln!("Filtros:");
|
||||
eprintln!(" --unit, -u <name> Filtra por unidad (e.g. foo.service)");
|
||||
eprintln!(" --source <s> journal | syslog");
|
||||
eprintln!(" --since, -S <secs> Sólo últimos N segundos");
|
||||
eprintln!(" --grep, -g <text> Contiene <text> en el body decoded");
|
||||
eprintln!(" --tail, -n <N> Últimas N entries");
|
||||
eprintln!("Output:");
|
||||
eprintln!(" --output, -o <fmt> pretty | json | export (systemd journal export)");
|
||||
eprintln!(" --json alias de --output json");
|
||||
}
|
||||
|
||||
fn index_path() -> PathBuf {
|
||||
let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") { d }
|
||||
else if let Ok(h) = std::env::var("HOME") { format!("{h}/.local/share") }
|
||||
else { "/var/lib".into() };
|
||||
PathBuf::from(base).join("ente").join("journal").join("index.log")
|
||||
}
|
||||
|
||||
fn now_ms() -> u128 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IndexEntry {
|
||||
timestamp_ms: u128,
|
||||
source: String,
|
||||
unit: String,
|
||||
sha_hex: String,
|
||||
}
|
||||
|
||||
fn parse_line(line: &str) -> Option<IndexEntry> {
|
||||
let mut parts = line.splitn(4, ':');
|
||||
let ts: u128 = parts.next()?.parse().ok()?;
|
||||
let source = parts.next()?.to_string();
|
||||
let unit = parts.next()?.to_string();
|
||||
let sha = parts.next()?.to_string();
|
||||
if sha.len() != 64 { return None; }
|
||||
Some(IndexEntry { timestamp_ms: ts, source, unit, sha_hex: sha })
|
||||
}
|
||||
|
||||
fn parse_sha(hex: &str) -> Option<[u8; 32]> {
|
||||
if hex.len() != 64 { return None; }
|
||||
let mut sha = [0u8; 32];
|
||||
for i in 0..32 {
|
||||
sha[i] = u8::from_str_radix(&hex[i*2..i*2+2], 16).ok()?;
|
||||
}
|
||||
Some(sha)
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let args = parse_args();
|
||||
let path = index_path();
|
||||
if !path.exists() {
|
||||
eprintln!("index no existe: {} — ¿journald-compat ha corrido?", path.display());
|
||||
std::process::exit(1);
|
||||
}
|
||||
let raw = std::fs::read_to_string(&path)?;
|
||||
let mut entries: Vec<IndexEntry> = raw.lines()
|
||||
.filter_map(parse_line)
|
||||
.collect();
|
||||
|
||||
// Filtros
|
||||
let now = now_ms();
|
||||
if let Some(secs) = args.since_secs {
|
||||
let cutoff = now.saturating_sub(secs as u128 * 1000);
|
||||
entries.retain(|e| e.timestamp_ms >= cutoff);
|
||||
}
|
||||
if let Some(unit) = &args.unit {
|
||||
entries.retain(|e| &e.unit == unit);
|
||||
}
|
||||
if let Some(src) = &args.source {
|
||||
entries.retain(|e| &e.source == src);
|
||||
}
|
||||
// tail después de filtros temporales/identidad pero antes de grep —
|
||||
// grep es post porque requiere cargar bytes del CAS.
|
||||
|
||||
let mut out: Vec<(IndexEntry, String)> = entries.into_iter()
|
||||
.filter_map(|e| {
|
||||
let sha = parse_sha(&e.sha_hex)?;
|
||||
let bytes = ente_cas::resolve(&sha).ok()?;
|
||||
let body = String::from_utf8_lossy(&bytes).into_owned();
|
||||
Some((e, body))
|
||||
})
|
||||
.collect();
|
||||
|
||||
if let Some(g) = &args.grep {
|
||||
out.retain(|(_, body)| body.contains(g.as_str()));
|
||||
}
|
||||
if let Some(n) = args.tail {
|
||||
let len = out.len();
|
||||
if len > n { out.drain(..len - n); }
|
||||
}
|
||||
|
||||
for (e, body) in out {
|
||||
match args.output {
|
||||
OutputFormat::Pretty => print_pretty(&e, &body),
|
||||
OutputFormat::Json => print_json(&e, &body),
|
||||
OutputFormat::Export => print_export(&e, &body),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_pretty(e: &IndexEntry, body: &str) {
|
||||
let secs = e.timestamp_ms / 1000;
|
||||
let ms = e.timestamp_ms % 1000;
|
||||
let header = if e.unit == "-" {
|
||||
format!("{}.{:03} [{}]", secs, ms, e.source)
|
||||
} else {
|
||||
format!("{}.{:03} [{}] {{{}}}", secs, ms, e.source, e.unit)
|
||||
};
|
||||
println!("{header}");
|
||||
// Si es journald native (KEY=value lines), extraer MESSAGE.
|
||||
if body.contains('=') && body.lines().any(|l| l.contains('=')) {
|
||||
for line in body.lines() {
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
if k.trim() == "MESSAGE" {
|
||||
println!(" {v}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for line in body.trim_end().lines() {
|
||||
println!(" {line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// systemd journal export format. Cada entry es un bloque de líneas
|
||||
/// `KEY=value\n` separado por blank line. Para values con newlines o
|
||||
/// bytes binarios, el formato usa una variante con length-prefix
|
||||
/// (8 bytes LE u64) — por simplicidad sólo emitimos values con texto
|
||||
/// que no contienen newlines o caracteres no-printables. Extraemos
|
||||
/// MESSAGE/PRIORITY/_SYSTEMD_UNIT del body si es journald native.
|
||||
///
|
||||
/// Compatible con `journalctl --input-format=export -m`.
|
||||
fn print_export(e: &IndexEntry, body: &str) {
|
||||
// Timestamps: __REALTIME_TIMESTAMP en µs, __MONOTONIC_TIMESTAMP también.
|
||||
let realtime_us = e.timestamp_ms.saturating_mul(1000);
|
||||
println!("__CURSOR=s={};t={};x={}",
|
||||
&e.sha_hex[..16], // pseudo-cursor: prefix del SHA
|
||||
realtime_us,
|
||||
&e.sha_hex[..8]);
|
||||
println!("__REALTIME_TIMESTAMP={}", realtime_us);
|
||||
println!("__MONOTONIC_TIMESTAMP={}", realtime_us);
|
||||
|
||||
let host = gethostname_safe();
|
||||
if !host.is_empty() {
|
||||
println!("_HOSTNAME={host}");
|
||||
}
|
||||
|
||||
if e.unit != "-" {
|
||||
println!("_SYSTEMD_UNIT={}", e.unit);
|
||||
}
|
||||
println!("_TRANSPORT={}", match e.source.as_str() {
|
||||
"syslog" => "syslog",
|
||||
"journal" => "journal",
|
||||
_ => "stdout",
|
||||
});
|
||||
|
||||
// Si el body es journald native (KEY=value lines), emitir cada uno
|
||||
// verbatim — son los fields originales del producer. Filtrar líneas
|
||||
// que no son seguras para export (con newlines en value, etc).
|
||||
if body.contains('=') && body.lines().any(|l| l.contains('=')) {
|
||||
for line in body.lines() {
|
||||
if line.contains('=') && line.bytes().all(safe_export_byte) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Syslog text — empaquetar como MESSAGE.
|
||||
let msg = body.trim_end()
|
||||
.replace('\n', " "); // collapsa newlines
|
||||
if msg.bytes().all(safe_export_byte) {
|
||||
println!("MESSAGE={msg}");
|
||||
}
|
||||
}
|
||||
// Blank line separa entries.
|
||||
println!();
|
||||
}
|
||||
|
||||
fn safe_export_byte(b: u8) -> bool {
|
||||
// ASCII printable, espacio, tab. No newlines (manejados aparte).
|
||||
(0x20..=0x7E).contains(&b) || b == b'\t'
|
||||
}
|
||||
|
||||
fn gethostname_safe() -> String {
|
||||
let mut buf = [0u8; 256];
|
||||
let r = unsafe {
|
||||
libc::gethostname(buf.as_mut_ptr() as *mut _, buf.len())
|
||||
};
|
||||
if r != 0 { return String::new(); }
|
||||
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
|
||||
std::str::from_utf8(&buf[..len]).unwrap_or("").to_string()
|
||||
}
|
||||
|
||||
fn print_json(e: &IndexEntry, body: &str) {
|
||||
// JSON-lines básico, sin dependencia de serde — formato simple y estable.
|
||||
let escaped_body = body
|
||||
.replace('\\', "\\\\")
|
||||
.replace('"', "\\\"")
|
||||
.replace('\n', "\\n")
|
||||
.replace('\r', "\\r")
|
||||
.replace('\t', "\\t");
|
||||
let unit_field = if e.unit == "-" { "null".to_string() }
|
||||
else { format!("\"{}\"", e.unit) };
|
||||
println!(
|
||||
r#"{{"timestamp_ms":{},"source":"{}","unit":{},"sha":"{}","body":"{}"}}"#,
|
||||
e.timestamp_ms, e.source, unit_field, e.sha_hex, escaped_body
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! ente-journald-compat: stub que absorbe escrituras al journal socket.
|
||||
//!
|
||||
//! Listen en `/run/systemd/journal/socket` (datagram) — todo lo que llega
|
||||
//! se decodifica best-effort y se emite como tracing event.
|
||||
//!
|
||||
//! Sin esto, apps que usan `sd_journal_send` o syslog fallan al escribir.
|
||||
//! Para una implementación real: persistir a CAS por timestamp+sha,
|
||||
//! exponer query API, indexar por unidad/usuario.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::os::fd::{AsRawFd, OwnedFd};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{debug, info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const JOURNAL_SOCKET: &str = "/run/systemd/journal/socket";
|
||||
const DEV_LOG: &str = "/dev/log";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-journald-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
// Intentamos vincular ambos sockets. Cada uno puede fallar
|
||||
// independientemente; si alguno funciona, seguimos.
|
||||
let mut bound = 0usize;
|
||||
if let Some(stream) = bind_dgram(JOURNAL_SOCKET) {
|
||||
bound += 1;
|
||||
spawn_listener(stream, "journal");
|
||||
} else {
|
||||
warn!(path = JOURNAL_SOCKET, "no se pudo bind — necesita CAP_NET_BIND_SERVICE o /run writable");
|
||||
}
|
||||
if let Some(stream) = bind_dgram(DEV_LOG) {
|
||||
bound += 1;
|
||||
spawn_listener(stream, "syslog");
|
||||
} else {
|
||||
warn!(path = DEV_LOG, "no se pudo bind /dev/log");
|
||||
}
|
||||
|
||||
if bound == 0 {
|
||||
warn!("ningún socket bound — modo idle");
|
||||
} else {
|
||||
info!(sockets_bound = bound, "journald-compat listening");
|
||||
}
|
||||
|
||||
wait_for_term().await
|
||||
}
|
||||
|
||||
fn bind_dgram(path: &str) -> Option<AsyncFd<OwnedFdWrap>> {
|
||||
use nix::sys::socket::{bind, socket, AddressFamily, SockFlag, SockType, UnixAddr};
|
||||
let _ = std::fs::remove_file(path);
|
||||
if let Some(parent) = Path::new(path).parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let fd = match socket(
|
||||
AddressFamily::Unix,
|
||||
SockType::Datagram,
|
||||
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
|
||||
None,
|
||||
) {
|
||||
Ok(f) => f,
|
||||
Err(e) => { warn!(?e, "socket() falló"); return None; }
|
||||
};
|
||||
let addr = match UnixAddr::new(path) {
|
||||
Ok(a) => a,
|
||||
Err(e) => { warn!(?e, "UnixAddr falló"); return None; }
|
||||
};
|
||||
if let Err(e) = bind(fd.as_raw_fd(), &addr) {
|
||||
warn!(?e, %path, "bind falló");
|
||||
return None;
|
||||
}
|
||||
AsyncFd::new(OwnedFdWrap(fd)).ok()
|
||||
}
|
||||
|
||||
struct OwnedFdWrap(OwnedFd);
|
||||
impl AsRawFd for OwnedFdWrap {
|
||||
fn as_raw_fd(&self) -> std::os::fd::RawFd { self.0.as_raw_fd() }
|
||||
}
|
||||
|
||||
fn spawn_listener(async_fd: AsyncFd<OwnedFdWrap>, source: &'static str) {
|
||||
tokio::spawn(async move {
|
||||
let mut buf = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
let mut guard = match async_fd.readable().await {
|
||||
Ok(g) => g,
|
||||
Err(e) => { warn!(?e, source, "readable failed"); return; }
|
||||
};
|
||||
let raw_fd = guard.get_inner().as_raw_fd();
|
||||
loop {
|
||||
let n = unsafe {
|
||||
libc::recv(raw_fd, buf.as_mut_ptr() as *mut _, buf.len(), 0)
|
||||
};
|
||||
if n <= 0 { break; }
|
||||
handle_message(&buf[..n as usize], source);
|
||||
}
|
||||
guard.clear_ready();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Mutex sobre el archivo index para escrituras concurrentes desde
|
||||
/// múltiples listeners (journal + syslog).
|
||||
static INDEX_FILE: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Path del index file: `$XDG_DATA_HOME/ente/journal/index.log` (default
|
||||
/// `~/.local/share/ente/journal/index.log`).
|
||||
fn index_path() -> PathBuf {
|
||||
let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") { d }
|
||||
else if let Ok(h) = std::env::var("HOME") { format!("{h}/.local/share") }
|
||||
else { "/var/lib".into() };
|
||||
PathBuf::from(base).join("ente").join("journal").join("index.log")
|
||||
}
|
||||
|
||||
fn now_ms() -> u128 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Persiste el blob crudo al CAS y appendea una línea al index:
|
||||
/// `<timestamp_ms>:<source>:<unit>:<sha_hex>`. Errores se logean pero
|
||||
/// no abortan — perder un mensaje no debe romper journald.
|
||||
fn persist_to_cas(buf: &[u8], source: &'static str, unit: Option<&str>) {
|
||||
let sha = match ente_cas::store(buf) {
|
||||
Ok(s) => s,
|
||||
Err(e) => { warn!(?e, "CAS store falló"); return; }
|
||||
};
|
||||
let line = format!(
|
||||
"{}:{}:{}:{}\n",
|
||||
now_ms(), source, unit.unwrap_or("-"), ente_cas::hex(&sha)
|
||||
);
|
||||
let path = index_path();
|
||||
let _guard = INDEX_FILE.lock().unwrap();
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut f = match std::fs::OpenOptions::new()
|
||||
.create(true).append(true)
|
||||
.open(&path)
|
||||
{
|
||||
Ok(f) => f,
|
||||
Err(e) => { warn!(?e, path = %path.display(), "abrir index"); return; }
|
||||
};
|
||||
if let Err(e) = f.write_all(line.as_bytes()) {
|
||||
warn!(?e, "write index");
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodifica best-effort. Formato journald nativo: lines de "KEY=value"
|
||||
/// (binario para values con newlines, pero raro). Formato syslog: texto
|
||||
/// con prefijo "<priority>tag: message".
|
||||
fn handle_message(buf: &[u8], source: &'static str) {
|
||||
if let Ok(s) = std::str::from_utf8(buf) {
|
||||
if s.contains('=') && s.lines().any(|l| l.contains('=')) {
|
||||
let mut message = None;
|
||||
let mut priority = None;
|
||||
let mut unit: Option<String> = None;
|
||||
for line in s.lines() {
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
match k {
|
||||
"MESSAGE" => message = Some(v.to_string()),
|
||||
"PRIORITY" => priority = Some(v.to_string()),
|
||||
"_SYSTEMD_UNIT" | "UNIT" => unit = Some(v.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
persist_to_cas(buf, source, unit.as_deref());
|
||||
if let Some(msg) = message {
|
||||
info!(target: "journal", source, ?priority, ?unit, "{msg}");
|
||||
} else {
|
||||
debug!(source, len = buf.len(), "journal native sin MESSAGE");
|
||||
}
|
||||
} else {
|
||||
persist_to_cas(buf, source, None);
|
||||
info!(target: "syslog", source, "{}", s.trim_end());
|
||||
}
|
||||
} else {
|
||||
persist_to_cas(buf, source, None);
|
||||
debug!(source, len = buf.len(), "journal binario (no UTF-8)");
|
||||
}
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Journal],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_journald_compat=info,journal=info,syslog=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "ente-kernel"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -0,0 +1,11 @@
|
||||
//! ente-kernel: primitivas de Linux que el Init usa pero que son reusables
|
||||
//! desde tools/tests/sub-supervisores. Sin estado global. Cada función es
|
||||
//! independiente y se puede testear de forma aislada.
|
||||
|
||||
pub mod sigchld;
|
||||
pub mod surface;
|
||||
pub mod uevent;
|
||||
|
||||
pub use sigchld::spawn_sigchld_stream;
|
||||
pub use surface::{become_child_subreaper, bootstrap_kernel_surface};
|
||||
pub use uevent::{spawn_uevent_stream, UAction, UEvent};
|
||||
@@ -0,0 +1,66 @@
|
||||
//! SIGCHLD vía signalfd, no signal handler.
|
||||
//!
|
||||
//! Los handlers async-signal sólo pueden invocar funciones async-signal-safe
|
||||
//! — no allocator, no `mpsc::send`. Con signalfd la señal entra al runtime de
|
||||
//! Tokio como un `fd` legible y la cosechamos en el bucle como cualquier otro
|
||||
//! evento. Esto es lo que hace que un init en Rust moderno sea sano.
|
||||
|
||||
use anyhow::Context;
|
||||
use nix::sys::signal::Signal;
|
||||
use nix::sys::signalfd::{SfdFlags, SigSet, SignalFd};
|
||||
use std::os::fd::AsRawFd;
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, trace};
|
||||
|
||||
/// Bloquea SIGCHLD para entrega asíncrona, abre signalfd, y emite un `()`
|
||||
/// en el canal cada vez que llega al menos una señal.
|
||||
pub fn spawn_sigchld_stream() -> anyhow::Result<mpsc::Receiver<()>> {
|
||||
let mut mask = SigSet::empty();
|
||||
mask.add(Signal::SIGCHLD);
|
||||
mask.thread_block().context("SIGCHLD thread_block")?;
|
||||
|
||||
let sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK | SfdFlags::SFD_CLOEXEC)
|
||||
.context("signalfd creation")?;
|
||||
|
||||
let async_fd = AsyncFd::new(SignalFdHandle(sfd)).context("AsyncFd::new")?;
|
||||
|
||||
let (tx, rx) = mpsc::channel(8);
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let mut guard = match async_fd.readable().await {
|
||||
Ok(g) => g,
|
||||
Err(e) => { error!(?e, "signalfd readable failed"); return; }
|
||||
};
|
||||
// Drenamos todas las siginfos pendientes; signalfd las coalesce
|
||||
// pero no las cuenta — un read por evento legible es suficiente.
|
||||
drain(guard.get_inner());
|
||||
guard.clear_ready();
|
||||
if tx.send(()).await.is_err() { return; }
|
||||
trace!("SIGCHLD batch coalesced");
|
||||
}
|
||||
});
|
||||
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
struct SignalFdHandle(SignalFd);
|
||||
|
||||
impl AsRawFd for SignalFdHandle {
|
||||
fn as_raw_fd(&self) -> std::os::fd::RawFd {
|
||||
self.0.as_raw_fd()
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(handle: &SignalFdHandle) {
|
||||
let fd = handle.as_raw_fd();
|
||||
// Tamaño exacto de signalfd_siginfo. Leemos en bucle hasta EAGAIN.
|
||||
let mut buf = [0u8; std::mem::size_of::<libc::signalfd_siginfo>()];
|
||||
loop {
|
||||
let n = unsafe {
|
||||
libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len())
|
||||
};
|
||||
if n < 0 { return; }
|
||||
if n == 0 { return; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Bootstrap del entorno kernel para PID 1: monta procfs/sysfs/devtmpfs/cgroup2
|
||||
//! y registra al proceso como subreaper para adoptar huérfanos.
|
||||
//!
|
||||
//! Idempotente: si los puntos de montaje ya existen (initramfs los montó),
|
||||
//! el segundo mount falla con EBUSY y simplemente lo ignoramos.
|
||||
|
||||
use anyhow::Context;
|
||||
use nix::mount::{mount, MsFlags};
|
||||
use tracing::debug;
|
||||
|
||||
/// Monta los pseudo-filesystems esenciales. Errores benignos (ya montados)
|
||||
/// se ignoran; errores serios se propagan.
|
||||
pub fn bootstrap_kernel_surface() -> anyhow::Result<()> {
|
||||
// Cada uno con sus flags estándar — NOSUID/NOEXEC/NODEV donde aplica.
|
||||
mount::<str, str, str, str>(
|
||||
Some("proc"), "/proc", Some("proc"),
|
||||
MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC | MsFlags::MS_NODEV, None,
|
||||
).ok();
|
||||
mount::<str, str, str, str>(
|
||||
Some("sysfs"), "/sys", Some("sysfs"),
|
||||
MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC | MsFlags::MS_NODEV, None,
|
||||
).ok();
|
||||
mount::<str, str, str, str>(
|
||||
Some("devtmpfs"), "/dev", Some("devtmpfs"),
|
||||
MsFlags::MS_NOSUID, None,
|
||||
).ok();
|
||||
mount::<str, str, str, str>(
|
||||
Some("cgroup2"), "/sys/fs/cgroup", Some("cgroup2"),
|
||||
MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC | MsFlags::MS_NODEV, None,
|
||||
).ok();
|
||||
debug!("kernel surface bootstrap completo");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// PR_SET_CHILD_SUBREAPER: que adoptemos huérfanos del fractal.
|
||||
///
|
||||
/// En PID 1 esto es redundante (el kernel ya lo hace), pero se deja explícito
|
||||
/// para que ente-zero corriendo como sub-init en un container mantenga la
|
||||
/// misma semántica.
|
||||
pub fn become_child_subreaper() -> anyhow::Result<()> {
|
||||
let r = unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1u64, 0u64, 0u64, 0u64) };
|
||||
if r != 0 {
|
||||
anyhow::bail!(
|
||||
"prctl PR_SET_CHILD_SUBREAPER falló: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cosechar zombis hasta vaciar la cola de niños muertos. Devuelve los
|
||||
/// PIDs cosechados con su estado, como tuplas.
|
||||
pub fn reap_all() -> Vec<ReapedChild> {
|
||||
use nix::errno::Errno;
|
||||
use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
|
||||
Ok(WaitStatus::Exited(pid, code)) => {
|
||||
out.push(ReapedChild { pid: pid.as_raw(), status: ReapStatus::Exited(code) });
|
||||
}
|
||||
Ok(WaitStatus::Signaled(pid, sig, _core)) => {
|
||||
out.push(ReapedChild { pid: pid.as_raw(), status: ReapStatus::Signaled(sig as i32) });
|
||||
}
|
||||
Ok(WaitStatus::StillAlive) => return out,
|
||||
Err(Errno::ECHILD) => return out,
|
||||
Err(_) => return out,
|
||||
Ok(_) => continue, // Stopped/Continued — irrelevantes
|
||||
}
|
||||
}
|
||||
// unreachable, satisface al borrow checker
|
||||
#[allow(unreachable_code)]
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReapedChild {
|
||||
pub pid: i32,
|
||||
pub status: ReapStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ReapStatus {
|
||||
Exited(i32),
|
||||
Signaled(i32),
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Stream de uevents del kernel vía NETLINK_KOBJECT_UEVENT.
|
||||
//!
|
||||
//! Bind requiere CAP_NET_ADMIN. En dev mode normal eso no está disponible —
|
||||
//! el caller debe estar preparado para que `spawn_uevent_stream` falle, y
|
||||
//! continuar sin grafo de dispositivos.
|
||||
|
||||
use anyhow::Context;
|
||||
use ente_card::DeviceClass;
|
||||
use nix::sys::socket::{bind, socket, AddressFamily, NetlinkAddr, SockFlag, SockProtocol, SockType};
|
||||
use std::collections::HashMap;
|
||||
use std::os::fd::{AsRawFd, OwnedFd};
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{trace, warn};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UEvent {
|
||||
pub action: UAction,
|
||||
pub devpath: String,
|
||||
pub subsystem: Option<String>,
|
||||
pub device_class: Option<DeviceClass>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum UAction {
|
||||
Add, Remove, Change, Move, Online, Offline, Bind, Unbind, Unknown,
|
||||
}
|
||||
|
||||
pub fn spawn_uevent_stream() -> anyhow::Result<mpsc::Receiver<UEvent>> {
|
||||
let fd: OwnedFd = socket(
|
||||
AddressFamily::Netlink,
|
||||
SockType::Datagram,
|
||||
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
|
||||
SockProtocol::NetlinkKObjectUEvent,
|
||||
).context("netlink socket")?;
|
||||
|
||||
// pid=0 → kernel asigna; groups=1 → multicast group del kernel uevent.
|
||||
let addr = NetlinkAddr::new(0, 1);
|
||||
bind(fd.as_raw_fd(), &addr).context("bind netlink uevent (CAP_NET_ADMIN?)")?;
|
||||
|
||||
let async_fd = AsyncFd::new(NetlinkHandle(fd)).context("AsyncFd::new(netlink)")?;
|
||||
let (tx, rx) = mpsc::channel(128);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut buf = vec![0u8; 16 * 1024];
|
||||
loop {
|
||||
let mut guard = match async_fd.readable().await {
|
||||
Ok(g) => g,
|
||||
Err(e) => { warn!(?e, "netlink readable"); return; }
|
||||
};
|
||||
let raw_fd = guard.get_inner().as_raw_fd();
|
||||
loop {
|
||||
let n = unsafe {
|
||||
libc::recv(raw_fd, buf.as_mut_ptr() as *mut _, buf.len(), 0)
|
||||
};
|
||||
if n <= 0 { break; }
|
||||
if let Some(evt) = parse_uevent(&buf[..n as usize]) {
|
||||
trace!(?evt.action, devpath = %evt.devpath, "uevent");
|
||||
if tx.send(evt).await.is_err() { return; }
|
||||
}
|
||||
}
|
||||
guard.clear_ready();
|
||||
}
|
||||
});
|
||||
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
struct NetlinkHandle(OwnedFd);
|
||||
impl AsRawFd for NetlinkHandle {
|
||||
fn as_raw_fd(&self) -> std::os::fd::RawFd { self.0.as_raw_fd() }
|
||||
}
|
||||
|
||||
fn parse_uevent(buf: &[u8]) -> Option<UEvent> {
|
||||
// udev re-emite mensajes con magic "libudev\0..." al multicast group 2.
|
||||
// Si llegan al grupo 1 (improbable con bind groups=1) los filtramos igual.
|
||||
if buf.starts_with(b"libudev\0") {
|
||||
return None;
|
||||
}
|
||||
let mut parts = buf.split(|b| *b == 0).filter(|s| !s.is_empty());
|
||||
let header = std::str::from_utf8(parts.next()?).ok()?;
|
||||
let (action_s, devpath) = header.split_once('@')?;
|
||||
let mut env: HashMap<String, String> = HashMap::new();
|
||||
for kv in parts {
|
||||
if let Ok(s) = std::str::from_utf8(kv) {
|
||||
if let Some((k, v)) = s.split_once('=') {
|
||||
env.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let subsystem = env.remove("SUBSYSTEM");
|
||||
let device_class = subsystem.as_deref().and_then(map_device_class);
|
||||
Some(UEvent {
|
||||
action: parse_action(action_s),
|
||||
devpath: devpath.to_string(),
|
||||
subsystem,
|
||||
device_class,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_action(s: &str) -> UAction {
|
||||
match s {
|
||||
"add" => UAction::Add,
|
||||
"remove" => UAction::Remove,
|
||||
"change" => UAction::Change,
|
||||
"move" => UAction::Move,
|
||||
"online" => UAction::Online,
|
||||
"offline" => UAction::Offline,
|
||||
"bind" => UAction::Bind,
|
||||
"unbind" => UAction::Unbind,
|
||||
_ => UAction::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_device_class(subsys: &str) -> Option<DeviceClass> {
|
||||
Some(match subsys {
|
||||
"block" => DeviceClass::Block,
|
||||
"tty" => DeviceClass::Tty,
|
||||
"input" => DeviceClass::Input,
|
||||
"drm" => DeviceClass::Drm,
|
||||
"net" => DeviceClass::Net,
|
||||
"hidraw" => DeviceClass::Hidraw,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_minimal_uevent() {
|
||||
let buf = b"add@/devices/foo\0ACTION=add\0DEVPATH=/devices/foo\0SUBSYSTEM=block\0";
|
||||
let evt = parse_uevent(buf).expect("parsed");
|
||||
assert_eq!(evt.action, UAction::Add);
|
||||
assert_eq!(evt.devpath, "/devices/foo");
|
||||
assert_eq!(evt.subsystem.as_deref(), Some("block"));
|
||||
assert!(matches!(evt.device_class, Some(DeviceClass::Block)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libudev_messages_filtered() {
|
||||
let buf = b"libudev\0\xfe\xed\xca\xfeadd@/devices/foo\0";
|
||||
assert!(parse_uevent(buf).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ente-localed-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-localed-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,219 @@
|
||||
//! ente-localed-compat: shim de `org.freedesktop.locale1`.
|
||||
//!
|
||||
//! GNOME settings panel "Region & Language" llama aquí. Properties leen
|
||||
//! /etc/locale.conf y /etc/vconsole.conf; setters log + forward.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::sync::Mutex;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.locale1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/locale1";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-localed-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = LocaleManager::default();
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "build conn falló — modo idle");
|
||||
wait_for_term().await
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
warn!(?e, "builder D-Bus falló — modo idle");
|
||||
wait_for_term().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct LocaleManager {
|
||||
transient_locale: Mutex<Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
#[interface(name = "org.freedesktop.locale1")]
|
||||
impl LocaleManager {
|
||||
/// Locale actual como array de "KEY=value" (LANG=en_US.UTF-8, LC_TIME=...).
|
||||
/// Default: leer /etc/locale.conf.
|
||||
#[zbus(property)]
|
||||
async fn locale(&self) -> Vec<String> {
|
||||
if let Some(v) = self.transient_locale.lock().unwrap().clone() {
|
||||
return v;
|
||||
}
|
||||
match std::fs::read_to_string("/etc/locale.conf") {
|
||||
Ok(c) => c.lines()
|
||||
.filter(|l| !l.trim().is_empty() && !l.starts_with('#'))
|
||||
.map(|s| s.trim().to_string())
|
||||
.collect(),
|
||||
Err(_) => vec!["LANG=C.UTF-8".into()],
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn x11layout(&self) -> String {
|
||||
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbLayout").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn x11model(&self) -> String {
|
||||
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbModel").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn x11variant(&self) -> String {
|
||||
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbVariant").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn x11options(&self) -> String {
|
||||
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbOptions").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn vconsole_keymap(&self) -> String {
|
||||
read_vconsole("KEYMAP").unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn vconsole_keymap_toggle(&self) -> String {
|
||||
read_vconsole("KEYMAP_TOGGLE").unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn set_locale(&self, locale: Vec<String>, _interactive: bool) -> fdo::Result<()> {
|
||||
// Validar formato KEY=value en cada entry.
|
||||
for entry in &locale {
|
||||
if !entry.contains('=') {
|
||||
return Err(fdo::Error::InvalidArgs(
|
||||
format!("locale entry inválido (sin '='): {entry}")
|
||||
));
|
||||
}
|
||||
}
|
||||
let content: String = locale.iter()
|
||||
.map(|s| format!("{s}\n"))
|
||||
.collect();
|
||||
atomic_write("/etc/locale.conf", content.as_bytes())
|
||||
.map_err(|e| fdo::Error::Failed(format!("write /etc/locale.conf: {e}")))?;
|
||||
*self.transient_locale.lock().unwrap() = Some(locale.clone());
|
||||
info!(?locale, "SetLocale → /etc/locale.conf");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_vconsole_keymap(
|
||||
&self,
|
||||
keymap: String,
|
||||
keymap_toggle: String,
|
||||
_convert: bool,
|
||||
_interactive: bool,
|
||||
) -> fdo::Result<()> {
|
||||
info!(%keymap, %keymap_toggle, "SetVConsoleKeymap (stub)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_x11_keyboard(
|
||||
&self,
|
||||
layout: String,
|
||||
model: String,
|
||||
variant: String,
|
||||
options: String,
|
||||
_convert: bool,
|
||||
_interactive: bool,
|
||||
) -> fdo::Result<()> {
|
||||
info!(%layout, %model, %variant, %options, "SetX11Keyboard (stub)");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn atomic_write(path: &str, content: &[u8]) -> std::io::Result<()> {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let p = std::path::Path::new(path);
|
||||
if let Some(parent) = p.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
let tmp = p.with_extension("tmp");
|
||||
{
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.create(true).write(true).truncate(true)
|
||||
.mode(0o644)
|
||||
.open(&tmp)?;
|
||||
f.write_all(content)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, p)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_kv(path: &str, key: &str) -> Option<String> {
|
||||
let content = std::fs::read_to_string(path).ok()?;
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with(&format!("Option \"{key}\"")) || trimmed.starts_with(key) {
|
||||
// Best-effort parse: tomar lo que está entre comillas.
|
||||
if let Some(start) = trimmed.find('"') {
|
||||
let rest = &trimmed[start + 1..];
|
||||
if let Some(end) = rest.find('"') {
|
||||
return Some(rest[..end].to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_vconsole(key: &str) -> Option<String> {
|
||||
let content = std::fs::read_to_string("/etc/vconsole.conf").ok()?;
|
||||
for line in content.lines() {
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
if k.trim() == key {
|
||||
return Some(v.trim().trim_matches('"').to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa2; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_localed_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ente-logind-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-logind-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,249 @@
|
||||
//! ente-logind-compat: el Ente que se hace pasar por systemd-logind.
|
||||
//!
|
||||
//! Vive FUERA de PID 1 — un parser D-Bus en el Init es una bomba con CVEs
|
||||
//! históricos. Ejecutado como hijo del Ente #0 con `Restart` supervision.
|
||||
//!
|
||||
//! Implementa el subset del interface `org.freedesktop.login1.Manager` que
|
||||
//! GNOME/KDE consultan en arranque. Cada método se traduce internamente en
|
||||
//! una request al bus interno del fractal — capacidades tipadas, no nombres
|
||||
//! D-Bus opacos hacia abajo.
|
||||
//!
|
||||
//! ## Lo que GNOME/KDE realmente llaman al boot
|
||||
//! - ListSessions, ListUsers, GetSession*
|
||||
//! - Inhibit (mantiene un fd vivo mientras la app está activa)
|
||||
//! - CanPowerOff/CanReboot/CanSuspend
|
||||
//! - PowerOff/Reboot/Suspend
|
||||
//! - Properties: IdleHint, Docked, etc.
|
||||
//!
|
||||
//! El stub responde "no hay sesiones" y "sí puedo apagar" — suficiente para
|
||||
//! que GNOME complete arranque sin marcar fallo.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface, zvariant::OwnedObjectPath, Connection};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.login1";
|
||||
const MANAGER_PATH: &str = "/org/freedesktop/login1";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-logind-compat: arrancando");
|
||||
|
||||
let bus_addr = std::env::var("DBUS_SYSTEM_BUS_ADDRESS")
|
||||
.unwrap_or_else(|_| "unix:path=/var/run/dbus/system_bus_socket".into());
|
||||
let bus_path = bus_addr.strip_prefix("unix:path=").unwrap_or(&bus_addr);
|
||||
let bus_present = std::path::Path::new(bus_path).exists();
|
||||
info!(bus_addr, bus_present, "configuración D-Bus");
|
||||
|
||||
// Anunciamos nuestra presencia al bus interno del fractal antes de
|
||||
// intentar registrar el nombre D-Bus. Esto sirve como handshake "estoy
|
||||
// vivo" independiente del estado del system bus.
|
||||
announce_to_fractal().await;
|
||||
|
||||
if !bus_present {
|
||||
warn!("system bus no disponible — modo idle (esperando SIGTERM)");
|
||||
return wait_for_term().await;
|
||||
}
|
||||
|
||||
let conn = match build_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!(?e, "fallo al registrar org.freedesktop.login1 — modo idle");
|
||||
// No retornamos error: la supervisión Restart entraría en bucle
|
||||
// si systemd-logind real ya posee el nombre. Esperar señal y salir.
|
||||
return wait_for_term().await;
|
||||
}
|
||||
};
|
||||
|
||||
info!("logind compat corriendo — esperando señales");
|
||||
let _ = conn; // mantener viva la conexión hasta SIGTERM
|
||||
wait_for_term().await
|
||||
}
|
||||
|
||||
async fn build_connection() -> anyhow::Result<Connection> {
|
||||
let manager = LogindManager::default();
|
||||
let conn = zbus::connection::Builder::system()?
|
||||
.name(BUS_NAME)?
|
||||
.serve_at(MANAGER_PATH, manager)?
|
||||
.build()
|
||||
.await?;
|
||||
info!(name = BUS_NAME, path = MANAGER_PATH, "name acquired + manager served");
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
match BusClient::from_env().await {
|
||||
Ok(mut client) => {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::LegacyLogind],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
Err(e) => warn!(?e, "no se pudo conectar al bus interno"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn forward_to_fractal(req: BusRequest) -> fdo::Result<()> {
|
||||
let mut client = BusClient::from_env().await
|
||||
.map_err(|e| fdo::Error::Failed(format!("bus client: {e}")))?;
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => Ok(()),
|
||||
Ok(BusResponse::Error(s)) => Err(fdo::Error::Failed(s)),
|
||||
Ok(other) => Err(fdo::Error::Failed(format!("respuesta inesperada: {other:?}"))),
|
||||
Err(e) => Err(fdo::Error::Failed(format!("bus call: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(60));
|
||||
tick.tick().await; // descartar el primer tick inmediato
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = term.recv() => { info!("SIGTERM — cierre ordenado"); return Ok(()); }
|
||||
_ = int_.recv() => { info!("SIGINT — cierre"); return Ok(()); }
|
||||
_ = tick.tick() => { info!("heartbeat"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_logind_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct LogindManager {
|
||||
/// Contador monótono de inhibits. Real impl mantendría una tabla con
|
||||
/// el fd vivo de cada uno y los enrutaría al bus interno del fractal.
|
||||
inhibit_counter: AtomicU32,
|
||||
}
|
||||
|
||||
/// Tipos del wire format de `org.freedesktop.login1.Manager`.
|
||||
type SessionTuple = (String, u32, String, String, OwnedObjectPath);
|
||||
type UserTuple = (u32, String, OwnedObjectPath);
|
||||
|
||||
#[interface(name = "org.freedesktop.login1.Manager")]
|
||||
impl LogindManager {
|
||||
// ---- Listado / lookup ----
|
||||
|
||||
async fn list_sessions(&self) -> fdo::Result<Vec<SessionTuple>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn list_users(&self) -> fdo::Result<Vec<UserTuple>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn get_session(&self, _session_id: String) -> fdo::Result<OwnedObjectPath> {
|
||||
Err(fdo::Error::Failed("no sessions in fractal".into()))
|
||||
}
|
||||
|
||||
async fn get_session_by_pid(&self, _pid: u32) -> fdo::Result<OwnedObjectPath> {
|
||||
Err(fdo::Error::Failed("no sessions in fractal".into()))
|
||||
}
|
||||
|
||||
async fn get_user(&self, _uid: u32) -> fdo::Result<OwnedObjectPath> {
|
||||
Err(fdo::Error::Failed("no users in fractal".into()))
|
||||
}
|
||||
|
||||
async fn get_user_by_pid(&self, _pid: u32) -> fdo::Result<OwnedObjectPath> {
|
||||
Err(fdo::Error::Failed("no users in fractal".into()))
|
||||
}
|
||||
|
||||
// ---- Inhibit ----
|
||||
//
|
||||
// Real: devuelve un fd que el cliente mantiene abierto mientras quiere
|
||||
// inhibir. Cuando lo cierra, sabemos que terminó. Aquí: stub que falla
|
||||
// con NotSupported — GNOME registra warning pero continúa el arranque.
|
||||
|
||||
async fn inhibit(
|
||||
&self,
|
||||
what: String,
|
||||
who: String,
|
||||
why: String,
|
||||
mode: String,
|
||||
) -> fdo::Result<zbus::zvariant::OwnedFd> {
|
||||
let n = self.inhibit_counter.fetch_add(1, Ordering::Relaxed);
|
||||
info!(n, %what, %who, %why, %mode, "Inhibit (stub)");
|
||||
Err(fdo::Error::NotSupported("Inhibit todavía no enruta al bus interno".into()))
|
||||
}
|
||||
|
||||
// ---- Power management ----
|
||||
|
||||
async fn power_off(&self, interactive: bool) -> fdo::Result<()> {
|
||||
info!(interactive, "PowerOff D-Bus → bus interno");
|
||||
forward_to_fractal(BusRequest::PowerOff { interactive }).await
|
||||
}
|
||||
|
||||
async fn reboot(&self, interactive: bool) -> fdo::Result<()> {
|
||||
info!(interactive, "Reboot D-Bus → bus interno");
|
||||
forward_to_fractal(BusRequest::Reboot { interactive }).await
|
||||
}
|
||||
|
||||
async fn suspend(&self, interactive: bool) -> fdo::Result<()> {
|
||||
info!(interactive, "Suspend D-Bus → bus interno");
|
||||
forward_to_fractal(BusRequest::Suspend { interactive }).await
|
||||
}
|
||||
|
||||
async fn hibernate(&self, interactive: bool) -> fdo::Result<()> {
|
||||
info!(interactive, "Hibernate D-Bus → bus interno");
|
||||
forward_to_fractal(BusRequest::Hibernate { interactive }).await
|
||||
}
|
||||
|
||||
async fn can_power_off(&self) -> fdo::Result<String> {
|
||||
Ok("yes".into())
|
||||
}
|
||||
|
||||
async fn can_reboot(&self) -> fdo::Result<String> {
|
||||
Ok("yes".into())
|
||||
}
|
||||
|
||||
async fn can_suspend(&self) -> fdo::Result<String> {
|
||||
// "challenge" = válido, requiere autenticación. GNOME muestra el
|
||||
// botón pero pide PIN/contraseña antes de invocar Suspend.
|
||||
Ok("challenge".into())
|
||||
}
|
||||
|
||||
async fn can_hibernate(&self) -> fdo::Result<String> {
|
||||
Ok("challenge".into())
|
||||
}
|
||||
|
||||
// ---- Properties mínimas ----
|
||||
|
||||
#[zbus(property)]
|
||||
async fn idle_hint(&self) -> bool { false }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn idle_since_hint(&self) -> u64 { 0 }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn idle_since_hint_monotonic(&self) -> u64 { 0 }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn block_inhibited(&self) -> String { String::new() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn delay_inhibited(&self) -> String { String::new() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn docked(&self) -> bool { false }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn lid_closed(&self) -> bool { false }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn on_external_power(&self) -> bool { true }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ente-machined-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-machined-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,186 @@
|
||||
//! ente-machined-compat: shim de `org.freedesktop.machine1`.
|
||||
//!
|
||||
//! systemd-machined trackea VMs y containers (typically managed por systemd-nspawn).
|
||||
//! En el fractal cada Ente con namespaces es candidato a "machine", pero la
|
||||
//! correspondencia no es 1:1 — un Ente puede tener menos aislamiento que una
|
||||
//! container completa.
|
||||
//!
|
||||
//! Este shim devuelve listas vacías para no romper clientes (gnome-boxes,
|
||||
//! virt-manager, etc) que llaman a `ListMachines` durante boot. Métodos de
|
||||
//! mutación (RegisterMachine, KillMachine) se aceptan como no-op con audit
|
||||
//! log via tracing.
|
||||
//!
|
||||
//! Producción real: integrar con el graph del fractal — ListMachines query
|
||||
//! BusRequest::ListEntes filtrado por `card.soma.namespaces.pid`.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::collections::HashMap;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface, zvariant::OwnedValue};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.machine1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/machine1";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-machined-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = MachineManager;
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
|
||||
},
|
||||
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
|
||||
}
|
||||
}
|
||||
|
||||
struct MachineManager;
|
||||
|
||||
/// Tipo del wire format de ListMachines: `(s, s, s, u, ay, ay, t, ay)` —
|
||||
/// name, class, service, leader_pid, root_directory_path, id_unix, time_obtained,
|
||||
/// machine_id_bytes. systemd usa este struct simplificado.
|
||||
type Machine = (String, String, String, u32, String);
|
||||
|
||||
#[interface(name = "org.freedesktop.machine1.Manager")]
|
||||
impl MachineManager {
|
||||
/// Lista vacía — no trackeamos containers todavía.
|
||||
async fn list_machines(&self) -> fdo::Result<Vec<Machine>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
/// Devuelve siempre NotFound — sin machines registradas.
|
||||
async fn get_machine(&self, name: String) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
|
||||
Err(fdo::Error::Failed(format!("machine '{name}' no encontrada")))
|
||||
}
|
||||
|
||||
async fn get_machine_by_pid(&self, pid: u32) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
|
||||
Err(fdo::Error::Failed(format!("PID {pid} no asociado a ninguna machine")))
|
||||
}
|
||||
|
||||
async fn register_machine(
|
||||
&self,
|
||||
name: String,
|
||||
_id: Vec<u8>,
|
||||
_service: String,
|
||||
class: String,
|
||||
_leader_pid: u32,
|
||||
_root_directory: String,
|
||||
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
|
||||
info!(%name, %class, "RegisterMachine (no-op)");
|
||||
Err(fdo::Error::NotSupported(
|
||||
"RegisterMachine no implementado — usar Cards del fractal".into()
|
||||
))
|
||||
}
|
||||
|
||||
async fn register_machine_with_network(
|
||||
&self,
|
||||
name: String,
|
||||
id: Vec<u8>,
|
||||
service: String,
|
||||
class: String,
|
||||
leader_pid: u32,
|
||||
root_directory: String,
|
||||
_network_interfaces: Vec<i32>,
|
||||
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
|
||||
self.register_machine(name, id, service, class, leader_pid, root_directory).await
|
||||
}
|
||||
|
||||
async fn create_machine(
|
||||
&self,
|
||||
name: String,
|
||||
_id: Vec<u8>,
|
||||
_service: String,
|
||||
class: String,
|
||||
_leader_pid: u32,
|
||||
_root_directory: String,
|
||||
_scope_properties: Vec<(String, OwnedValue)>,
|
||||
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
|
||||
info!(%name, %class, "CreateMachine (no-op)");
|
||||
Err(fdo::Error::NotSupported(
|
||||
"CreateMachine no implementado".into()
|
||||
))
|
||||
}
|
||||
|
||||
async fn terminate_machine(&self, name: String) -> fdo::Result<()> {
|
||||
info!(%name, "TerminateMachine (no-op)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn kill_machine(&self, name: String, _who: String, _signal: i32) -> fdo::Result<()> {
|
||||
info!(%name, "KillMachine (no-op)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_machine_address(&self, name: String) -> fdo::Result<Vec<(i32, Vec<u8>)>> {
|
||||
warn!(%name, "GetMachineAddress (sin tracking, devuelvo vacío)");
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn get_machine_osrelease(&self, name: String) -> fdo::Result<HashMap<String, String>> {
|
||||
warn!(%name, "GetMachineOSRelease (sin tracking)");
|
||||
Ok(HashMap::new())
|
||||
}
|
||||
|
||||
/// Operaciones sobre la "host machine" (PID 1 namespace) — siempre
|
||||
/// disponibles. Usamos el path canónico `/org/freedesktop/machine1/machine/_host`.
|
||||
async fn open_machine_login(&self, _name: String) -> fdo::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedFd)> {
|
||||
Err(fdo::Error::NotSupported(
|
||||
"OpenMachineLogin no implementado".into()
|
||||
))
|
||||
}
|
||||
|
||||
async fn open_machine_shell(
|
||||
&self,
|
||||
_name: String,
|
||||
_user: String,
|
||||
_path: String,
|
||||
_args: Vec<String>,
|
||||
_environment: Vec<String>,
|
||||
) -> fdo::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedFd)> {
|
||||
Err(fdo::Error::NotSupported("OpenMachineShell no implementado".into()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa5; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_machined_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "ente-notify-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-notify-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,160 @@
|
||||
//! ente-notify-compat: NOTIFY_SOCKET listener para apps `Type=notify`.
|
||||
//!
|
||||
//! systemd convention: el servicio escribe `KEY=value\n` lines a un socket
|
||||
//! datagram cuya path está en `$NOTIFY_SOCKET`. Keys típicos:
|
||||
//! - READY=1 (servicio listo para recibir requests)
|
||||
//! - STATUS=text (descripción del estado)
|
||||
//! - WATCHDOG=1 (heartbeat)
|
||||
//! - STOPPING=1 (cierre ordenado)
|
||||
//! - MAINPID=<pid> (cambio de PID principal)
|
||||
//!
|
||||
//! Path canonical: /run/systemd/notify. Bindeable sólo con CAP_NET_BIND_SERVICE
|
||||
//! o si /run es writable.
|
||||
//!
|
||||
//! Para que las apps lo usen, ente-soma debe inyectar `NOTIFY_SOCKET=<path>`
|
||||
//! en el envp de cada Ente encarnado. Eso ya lo hace via build_env() —
|
||||
//! aquí sólo necesitamos que el path sea coherente.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::os::fd::{AsRawFd, OwnedFd};
|
||||
use std::path::Path;
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{debug, info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const NOTIFY_SOCKET_PATH: &str = "/run/systemd/notify";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!(path = NOTIFY_SOCKET_PATH, "ente-notify-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let stream = match bind_dgram(NOTIFY_SOCKET_PATH) {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
warn!("no se pudo bind — modo idle (apps Type=notify caerán a no-op)");
|
||||
return wait_for_term().await;
|
||||
}
|
||||
};
|
||||
info!("NOTIFY_SOCKET listening");
|
||||
spawn_listener(stream);
|
||||
wait_for_term().await
|
||||
}
|
||||
|
||||
fn bind_dgram(path: &str) -> Option<AsyncFd<OwnedFdWrap>> {
|
||||
use nix::sys::socket::{bind, socket, AddressFamily, SockFlag, SockType, UnixAddr};
|
||||
let _ = std::fs::remove_file(path);
|
||||
if let Some(parent) = Path::new(path).parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let fd = socket(
|
||||
AddressFamily::Unix,
|
||||
SockType::Datagram,
|
||||
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
|
||||
None,
|
||||
).ok()?;
|
||||
let addr = UnixAddr::new(path).ok()?;
|
||||
if let Err(e) = bind(fd.as_raw_fd(), &addr) {
|
||||
warn!(?e, %path, "bind");
|
||||
return None;
|
||||
}
|
||||
// Permisos abiertos: cualquier proceso debería poder escribir notificaciones.
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o666));
|
||||
AsyncFd::new(OwnedFdWrap(fd)).ok()
|
||||
}
|
||||
|
||||
struct OwnedFdWrap(OwnedFd);
|
||||
impl AsRawFd for OwnedFdWrap {
|
||||
fn as_raw_fd(&self) -> std::os::fd::RawFd { self.0.as_raw_fd() }
|
||||
}
|
||||
|
||||
fn spawn_listener(async_fd: AsyncFd<OwnedFdWrap>) {
|
||||
tokio::spawn(async move {
|
||||
let mut buf = vec![0u8; 16 * 1024];
|
||||
loop {
|
||||
let mut guard = match async_fd.readable().await {
|
||||
Ok(g) => g,
|
||||
Err(e) => { warn!(?e, "readable"); return; }
|
||||
};
|
||||
let raw_fd = guard.get_inner().as_raw_fd();
|
||||
loop {
|
||||
let n = unsafe { libc::recv(raw_fd, buf.as_mut_ptr() as *mut _, buf.len(), 0) };
|
||||
if n <= 0 { break; }
|
||||
handle_notification(&buf[..n as usize]);
|
||||
}
|
||||
guard.clear_ready();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn handle_notification(buf: &[u8]) {
|
||||
let s = match std::str::from_utf8(buf) {
|
||||
Ok(s) => s,
|
||||
Err(_) => { debug!(len = buf.len(), "notify binario, skip"); return; }
|
||||
};
|
||||
let mut ready = false;
|
||||
let mut status = None;
|
||||
let mut mainpid = None;
|
||||
let mut watchdog = false;
|
||||
let mut stopping = false;
|
||||
let mut other_keys = Vec::new();
|
||||
for line in s.lines() {
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
match k {
|
||||
"READY" if v == "1" => ready = true,
|
||||
"STATUS" => status = Some(v.to_string()),
|
||||
"MAINPID" => mainpid = v.parse::<u32>().ok(),
|
||||
"WATCHDOG" if v == "1" => watchdog = true,
|
||||
"STOPPING" if v == "1" => stopping = true,
|
||||
_ => other_keys.push(format!("{k}={v}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
if ready {
|
||||
info!(?status, ?mainpid, "sd_notify READY");
|
||||
} else if stopping {
|
||||
info!(?status, "sd_notify STOPPING");
|
||||
} else if watchdog {
|
||||
debug!("sd_notify WATCHDOG");
|
||||
} else if let Some(s) = status {
|
||||
info!(%s, "sd_notify STATUS");
|
||||
} else if !other_keys.is_empty() {
|
||||
debug!(keys = ?other_keys, "sd_notify (other)");
|
||||
}
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa7; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_notify_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "ente-policy-provider"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-policy-provider"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,221 @@
|
||||
//! ente-policy-provider: Ente que arbitra autorizaciones de Polkit.
|
||||
//!
|
||||
//! Se anuncia como proveedor de `POLKIT_DECISION_IFACE` en el bus interno.
|
||||
//! Cuando `ente-polkit-compat` recibe `CheckAuthorization` D-Bus, forwarda
|
||||
//! a este Ente vía Invoke. Aquí decidimos sí/no según política configurada.
|
||||
//!
|
||||
//! Wire format del blob de entrada: `pid_be_u32 | uid_be_u32 | action_id_utf8`.
|
||||
//! Respuesta: `[decision_byte]` — 1 = allow, 0 = deny.
|
||||
//!
|
||||
//! Política se carga de `/etc/ente/policy.json` (o ruta override por env
|
||||
//! `ENTE_POLICY_FILE`). Formato:
|
||||
//! ```json
|
||||
//! {
|
||||
//! "default": "allow",
|
||||
//! "rules": [
|
||||
//! { "match": "org.freedesktop.hostname1.*", "decision": "allow" },
|
||||
//! { "match": "org.freedesktop.login1.power-off", "require_uid": 0 },
|
||||
//! { "match": "*.set-*", "decision": "deny", "audit": true }
|
||||
//! ]
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use ente_bus::{BusResponse, BusServer, InvokeHandler, POLKIT_DECISION_IFACE};
|
||||
use ente_card::Capability;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct PolicyConfig {
|
||||
#[serde(default = "default_decision")]
|
||||
default: Decision,
|
||||
#[serde(default)]
|
||||
rules: Vec<Rule>,
|
||||
}
|
||||
|
||||
fn default_decision() -> Decision { Decision::Allow }
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Decision { Allow, Deny }
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct Rule {
|
||||
/// Glob simple: `*` = wildcard. `org.freedesktop.hostname1.*` matchea
|
||||
/// cualquier action_id con ese prefijo.
|
||||
r#match: String,
|
||||
#[serde(default)]
|
||||
decision: Option<Decision>,
|
||||
/// Si presente, sólo este uid pasa. Otros se denegen.
|
||||
#[serde(default)]
|
||||
require_uid: Option<u32>,
|
||||
/// Si presente, sólo este pid pasa.
|
||||
#[serde(default)]
|
||||
require_pid: Option<u32>,
|
||||
#[serde(default)]
|
||||
audit: bool,
|
||||
}
|
||||
|
||||
impl Default for PolicyConfig {
|
||||
fn default() -> Self {
|
||||
// Default sensato: caps escaladas requieren uid 0; el resto allow.
|
||||
Self {
|
||||
default: Decision::Allow,
|
||||
rules: vec![
|
||||
// Power management: cualquiera puede pedir el reboot,
|
||||
// pero la decisión final está en el holder de Capability::Spawn.
|
||||
Rule {
|
||||
r#match: "org.freedesktop.login1.set-wall-message".into(),
|
||||
decision: Some(Decision::Allow), require_uid: None, require_pid: None, audit: true,
|
||||
},
|
||||
// hostname/timezone/locale: requieren root.
|
||||
Rule {
|
||||
r#match: "org.freedesktop.hostname1.*".into(),
|
||||
decision: None, require_uid: Some(0), require_pid: None, audit: true,
|
||||
},
|
||||
Rule {
|
||||
r#match: "org.freedesktop.timedate1.*".into(),
|
||||
decision: None, require_uid: Some(0), require_pid: None, audit: true,
|
||||
},
|
||||
Rule {
|
||||
r#match: "org.freedesktop.locale1.*".into(),
|
||||
decision: None, require_uid: Some(0), require_pid: None, audit: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-policy-provider: arrancando");
|
||||
|
||||
let policy = load_policy();
|
||||
info!(rules = policy.rules.len(), default = ?policy.default, "policy cargada");
|
||||
|
||||
let handler = PolicyHandler { policy: Arc::new(policy) };
|
||||
|
||||
tokio::spawn(async {
|
||||
let mut term = signal(SignalKind::terminate()).unwrap();
|
||||
let mut int_ = signal(SignalKind::interrupt()).unwrap();
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
std::process::exit(0);
|
||||
});
|
||||
|
||||
// Una única conexión: announce + serve. Bidirectional bajo el hood.
|
||||
let mut server = BusServer::from_env().await?;
|
||||
server.announce(vec![Capability::Endpoint {
|
||||
interface: POLKIT_DECISION_IFACE,
|
||||
version: 1,
|
||||
}]).await?;
|
||||
info!("Announce OK; sirviendo invokes de policy decision");
|
||||
server.serve(handler).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct PolicyHandler {
|
||||
policy: Arc<PolicyConfig>,
|
||||
}
|
||||
|
||||
impl InvokeHandler for PolicyHandler {
|
||||
fn handle(&mut self, cap: Capability, blob: Vec<u8>) -> BusResponse {
|
||||
// Validar cap (defensa contra forwarding a interface incorrecto).
|
||||
if !matches!(&cap, Capability::Endpoint { interface, .. } if *interface == POLKIT_DECISION_IFACE) {
|
||||
return BusResponse::Error(format!("policy-provider: cap inesperado {cap:?}"));
|
||||
}
|
||||
// Decodificar blob: [pid:4][uid:4][action_id...]
|
||||
if blob.len() < 8 {
|
||||
return BusResponse::Error("blob demasiado corto (esperado pid|uid|action_id)".into());
|
||||
}
|
||||
let pid = u32::from_be_bytes(blob[0..4].try_into().unwrap());
|
||||
let uid = u32::from_be_bytes(blob[4..8].try_into().unwrap());
|
||||
let action_id = match std::str::from_utf8(&blob[8..]) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return BusResponse::Error("action_id no es UTF-8".into()),
|
||||
};
|
||||
|
||||
let decision = decide(&self.policy, action_id, pid, uid);
|
||||
let byte = if decision == Decision::Allow { 1u8 } else { 0u8 };
|
||||
info!(action_id, pid, uid, ?decision, "policy decision");
|
||||
BusResponse::Invoked { result: vec![byte] }
|
||||
}
|
||||
}
|
||||
|
||||
fn decide(policy: &PolicyConfig, action_id: &str, pid: u32, uid: u32) -> Decision {
|
||||
for rule in &policy.rules {
|
||||
if !glob_match(&rule.r#match, action_id) { continue; }
|
||||
if let Some(req_uid) = rule.require_uid {
|
||||
if uid != req_uid {
|
||||
if rule.audit {
|
||||
info!(action_id, uid, req_uid, "AUDIT: deny por uid mismatch");
|
||||
}
|
||||
return Decision::Deny;
|
||||
}
|
||||
}
|
||||
if let Some(req_pid) = rule.require_pid {
|
||||
if pid != req_pid {
|
||||
if rule.audit {
|
||||
info!(action_id, pid, req_pid, "AUDIT: deny por pid mismatch");
|
||||
}
|
||||
return Decision::Deny;
|
||||
}
|
||||
}
|
||||
if let Some(d) = rule.decision {
|
||||
if rule.audit {
|
||||
info!(action_id, ?d, "AUDIT: rule match con decisión explícita");
|
||||
}
|
||||
return d;
|
||||
}
|
||||
// Rule matched pero sin decisión explícita (sólo require_*) y todos
|
||||
// los requires pasaron — caemos al default.
|
||||
if rule.audit {
|
||||
info!(action_id, ?policy.default, "AUDIT: rule match → default");
|
||||
}
|
||||
return policy.default;
|
||||
}
|
||||
policy.default
|
||||
}
|
||||
|
||||
/// Glob simple: `*` matchea cualquier cosa. Soporta prefix (`foo.*`),
|
||||
/// suffix (`*.bar`) y wildcard exacto (`*`). No es PCRE — intencional.
|
||||
fn glob_match(pattern: &str, target: &str) -> bool {
|
||||
if pattern == "*" { return true; }
|
||||
if let Some(prefix) = pattern.strip_suffix(".*") {
|
||||
return target == prefix || target.starts_with(&format!("{prefix}."));
|
||||
}
|
||||
if let Some(suffix) = pattern.strip_prefix("*.") {
|
||||
return target == suffix || target.ends_with(&format!(".{suffix}"));
|
||||
}
|
||||
pattern == target
|
||||
}
|
||||
|
||||
fn load_policy() -> PolicyConfig {
|
||||
let path = std::env::var("ENTE_POLICY_FILE")
|
||||
.unwrap_or_else(|_| "/etc/ente/policy.json".into());
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(content) => match serde_json::from_str(&content) {
|
||||
Ok(p) => { info!(path, "policy file cargado"); p }
|
||||
Err(e) => {
|
||||
warn!(?e, path, "policy file inválido, usando defaults");
|
||||
PolicyConfig::default()
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
info!(path, "policy file ausente — usando defaults conservadores");
|
||||
PolicyConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_policy_provider=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ente-polkit-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-polkit-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,262 @@
|
||||
//! ente-polkit-compat: shim de `org.freedesktop.PolicyKit1.Authority`.
|
||||
//!
|
||||
//! Polkit autoriza llamadas privilegiadas (e.g. SetHostname, PowerOff).
|
||||
//! En el fractal no usamos polkit como gatekeeper — la auth se hace en
|
||||
//! el bus interno via SO_PEERCRED y capability grants. Pero apps que
|
||||
//! usan polkit (gnome-control-center, etc) bloquean en `CheckAuthorization`
|
||||
//! si no responde nadie.
|
||||
//!
|
||||
//! Este shim responde "is_authorized=true" siempre — el fractal queda
|
||||
//! como sistema confiado. El logging deja audit trail de qué acciones se
|
||||
//! han pedido para futuro análisis.
|
||||
//!
|
||||
//! Producción real: integrar con el grant system del bus interno —
|
||||
//! CheckAuthorization solicita un token al graph y devuelve true/false
|
||||
//! según el resultado.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse, POLKIT_DECISION_IFACE, POLKIT_SERVICE_IFACE};
|
||||
use ente_card::Capability;
|
||||
use std::collections::HashMap;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{debug, info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface, zvariant::OwnedValue};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.PolicyKit1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/Authority";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-polkit-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = PolkitAuthority;
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
|
||||
},
|
||||
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
|
||||
}
|
||||
}
|
||||
|
||||
struct PolkitAuthority;
|
||||
|
||||
/// Wire format de Polkit: `Subject = (s, a{sv})` — kind ("unix-session",
|
||||
/// "unix-process", "system-bus-name") + detalles. El detail típico:
|
||||
/// {"pid": u32, "start-time": u64, "uid": u32}
|
||||
type Subject = (String, HashMap<String, OwnedValue>);
|
||||
|
||||
/// Resultado de `CheckAuthorization`: `(b, b, a{ss})` —
|
||||
/// is_authorized, is_challenge, details.
|
||||
type AuthResult = (bool, bool, HashMap<String, String>);
|
||||
|
||||
#[interface(name = "org.freedesktop.PolicyKit1.Authority")]
|
||||
impl PolkitAuthority {
|
||||
async fn check_authorization(
|
||||
&self,
|
||||
subject: Subject,
|
||||
action_id: String,
|
||||
_details: HashMap<String, String>,
|
||||
_flags: u32,
|
||||
_cancellation_id: String,
|
||||
) -> fdo::Result<AuthResult> {
|
||||
let (subj_kind, subj_details) = subject;
|
||||
let pid = subj_details.get("pid")
|
||||
.and_then(|v| u32::try_from(v).ok());
|
||||
let uid = subj_details.get("uid")
|
||||
.and_then(|v| u32::try_from(v).ok());
|
||||
|
||||
// Pregunta al bus interno del fractal si hay un policy provider.
|
||||
// Si lo hay, su decisión gobierna. Si no (NoProvider), default = allow.
|
||||
let decision = query_policy(&action_id, pid, uid).await;
|
||||
info!(%action_id, %subj_kind, ?pid, ?uid, ?decision, "CheckAuthorization");
|
||||
Ok((decision.allow, false, HashMap::new()))
|
||||
}
|
||||
|
||||
async fn check_authorization_by_async(
|
||||
&self,
|
||||
subject: Subject,
|
||||
action_id: String,
|
||||
details: HashMap<String, String>,
|
||||
flags: u32,
|
||||
cancellation_id: String,
|
||||
) -> fdo::Result<AuthResult> {
|
||||
// Mismo comportamiento; algunos clientes llaman la versión async.
|
||||
self.check_authorization(subject, action_id, details, flags, cancellation_id).await
|
||||
}
|
||||
|
||||
async fn cancel_check_authorization(&self, _cancellation_id: String) -> fdo::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn enumerate_actions(&self, _locale: String) -> fdo::Result<Vec<EnumeratedAction>> {
|
||||
// Devolvemos lista vacía — no enumeramos acciones registradas.
|
||||
// El llamador (típicamente gnome-control-center settings panel)
|
||||
// debería degradar grácilmente.
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn register_authentication_agent(
|
||||
&self,
|
||||
_subject: Subject,
|
||||
_locale: String,
|
||||
_object_path: String,
|
||||
) -> fdo::Result<()> {
|
||||
info!("RegisterAuthenticationAgent (no-op)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn register_authentication_agent_with_options(
|
||||
&self,
|
||||
_subject: Subject,
|
||||
_locale: String,
|
||||
_object_path: String,
|
||||
_options: HashMap<String, OwnedValue>,
|
||||
) -> fdo::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn unregister_authentication_agent(
|
||||
&self,
|
||||
_subject: Subject,
|
||||
_object_path: String,
|
||||
) -> fdo::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn authentication_agent_response(
|
||||
&self,
|
||||
_cookie: String,
|
||||
_identity: (String, HashMap<String, OwnedValue>),
|
||||
) -> fdo::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn enumerate_temporary_authorizations(
|
||||
&self,
|
||||
_subject: Subject,
|
||||
) -> fdo::Result<Vec<TemporaryAuth>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn revoke_temporary_authorizations(&self, _subject: Subject) -> fdo::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn revoke_temporary_authorization_by_id(&self, _id: String) -> fdo::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn backend_name(&self) -> String { "ente-polkit-compat".into() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn backend_version(&self) -> String { env!("CARGO_PKG_VERSION").into() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn backend_features(&self) -> u32 { 0 }
|
||||
}
|
||||
|
||||
/// Wire signature de EnumerateActions item:
|
||||
/// `(ssssssuusa{ss})` — action_id, descripción, message, vendor, vendor_url,
|
||||
/// icon_name, implicit_any, implicit_inactive, implicit_active, annotations.
|
||||
type EnumeratedAction = (
|
||||
String, String, String, String, String, String,
|
||||
u32, u32, String, HashMap<String, String>,
|
||||
);
|
||||
|
||||
/// Wire signature de TemporaryAuthorization:
|
||||
/// `(sssss)` — id, action_id, subject_kind, subject_detail, time_obtained, time_expires.
|
||||
/// Aquí `(string)` * 5 + 2 timestamps. Simplificamos al subset relevante.
|
||||
type TemporaryAuth = (String, String, (String, HashMap<String, OwnedValue>), u64, u64);
|
||||
|
||||
/// Resultado de una consulta de policy al fractal.
|
||||
#[derive(Debug)]
|
||||
struct PolicyDecision {
|
||||
allow: bool,
|
||||
/// Origen: "fractal" si vino del bus, "default-allow" si no había proveedor.
|
||||
source: &'static str,
|
||||
}
|
||||
|
||||
/// Pregunta al bus interno: ¿hay alguien que decida sobre `action_id`?
|
||||
/// Wire format del blob: `pid_u32_be | uid_u32_be | action_id_utf8`.
|
||||
/// El proveedor responde con `Invoked { result: [0|1] }` — 1 = allow.
|
||||
async fn query_policy(action_id: &str, pid: Option<u32>, uid: Option<u32>) -> PolicyDecision {
|
||||
let mut blob = Vec::with_capacity(8 + action_id.len());
|
||||
blob.extend_from_slice(&pid.unwrap_or(0).to_be_bytes());
|
||||
blob.extend_from_slice(&uid.unwrap_or(0).to_be_bytes());
|
||||
blob.extend_from_slice(action_id.as_bytes());
|
||||
|
||||
let mut client = match BusClient::from_env().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
debug!(?e, "no bus client — default allow");
|
||||
return PolicyDecision { allow: true, source: "no-bus" };
|
||||
}
|
||||
};
|
||||
let req = BusRequest::Invoke {
|
||||
cap: Capability::Endpoint {
|
||||
interface: POLKIT_DECISION_IFACE,
|
||||
version: 1,
|
||||
},
|
||||
blob,
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Invoked { result }) => {
|
||||
let allow = result.first().copied().unwrap_or(1) != 0;
|
||||
PolicyDecision { allow, source: "fractal" }
|
||||
}
|
||||
Ok(BusResponse::Error(msg)) if msg.contains("sin proveedor") => {
|
||||
// No hay policy provider — default allow.
|
||||
PolicyDecision { allow: true, source: "default-allow" }
|
||||
}
|
||||
Ok(other) => {
|
||||
warn!(?other, "policy: respuesta inesperada — default allow");
|
||||
PolicyDecision { allow: true, source: "default-allow" }
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "policy: bus call falló — default allow");
|
||||
PolicyDecision { allow: true, source: "default-allow" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: POLKIT_SERVICE_IFACE,
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_polkit_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "ente-resolved-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-resolved-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,210 @@
|
||||
//! ente-resolved-compat: shim de `org.freedesktop.resolve1`.
|
||||
//!
|
||||
//! Bajo el capó usa `tokio::net::lookup_host` (que termina en getaddrinfo
|
||||
//! del libc del sistema). No reimplementamos un resolver DNS — delegamos
|
||||
//! al stack de resolución del kernel/glibc.
|
||||
//!
|
||||
//! Métodos cubiertos:
|
||||
//! - ResolveHostname (name → addresses)
|
||||
//! - ResolveAddress (address → name reverse)
|
||||
//! - ResolveRecord (TXT/SRV/etc) — NotSupported (requiere DNS query directa)
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::net::IpAddr;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.resolve1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/resolve1";
|
||||
|
||||
const AF_INET: i32 = 2;
|
||||
const AF_INET6: i32 = 10;
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-resolved-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = ResolveManager;
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
|
||||
},
|
||||
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
|
||||
}
|
||||
}
|
||||
|
||||
struct ResolveManager;
|
||||
|
||||
/// Tipo del wire format de `ResolveHostname`. Por entry: (ifindex, family,
|
||||
/// address-as-bytes). systemd-resolved devuelve hasta 4 bytes para AF_INET
|
||||
/// y 16 para AF_INET6.
|
||||
type HostnameAddress = (i32, i32, Vec<u8>);
|
||||
|
||||
#[interface(name = "org.freedesktop.resolve1.Manager")]
|
||||
impl ResolveManager {
|
||||
/// Wire signature: `ResolveHostname(in iiusst, out a(iiay)st)` — recibe
|
||||
/// (ifindex, name, family, flags), devuelve (addresses, canonical, flags).
|
||||
async fn resolve_hostname(
|
||||
&self,
|
||||
_ifindex: i32,
|
||||
name: String,
|
||||
family: i32,
|
||||
_flags: u64,
|
||||
) -> fdo::Result<(Vec<HostnameAddress>, String, u64)> {
|
||||
// tokio::net::lookup_host requiere "host:port"; usamos puerto sentinel.
|
||||
let target = format!("{name}:0");
|
||||
let addrs = match tokio::net::lookup_host(&target).await {
|
||||
Ok(it) => it,
|
||||
Err(e) => return Err(fdo::Error::Failed(format!("lookup_host {name}: {e}"))),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for sa in addrs {
|
||||
let ip = sa.ip();
|
||||
let (af, bytes) = match ip {
|
||||
IpAddr::V4(v4) => (AF_INET, v4.octets().to_vec()),
|
||||
IpAddr::V6(v6) => (AF_INET6, v6.octets().to_vec()),
|
||||
};
|
||||
// Filtrado por family si el llamador lo pidió específico.
|
||||
if family != 0 && family != af { continue; }
|
||||
out.push((0i32, af, bytes));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(fdo::Error::Failed(format!("sin resoluciones para {name} (family={family})")));
|
||||
}
|
||||
info!(%name, family, count = out.len(), "ResolveHostname");
|
||||
Ok((out, name, 0))
|
||||
}
|
||||
|
||||
/// Wire signature: `ResolveAddress(in iiayt, out a(is)t)` — (ifindex,
|
||||
/// family, address, flags) → (names, flags).
|
||||
async fn resolve_address(
|
||||
&self,
|
||||
_ifindex: i32,
|
||||
family: i32,
|
||||
address: Vec<u8>,
|
||||
_flags: u64,
|
||||
) -> fdo::Result<(Vec<(i32, String)>, u64)> {
|
||||
let ip = parse_address(family, &address)
|
||||
.ok_or_else(|| fdo::Error::InvalidArgs(format!("address malformado family={family} bytes={}", address.len())))?;
|
||||
// Reverse lookup vía getnameinfo. Usamos std::net::lookup_addr no existe,
|
||||
// así que invocamos via libc directamente.
|
||||
let name = reverse_lookup(ip)
|
||||
.ok_or_else(|| fdo::Error::Failed(format!("sin reverse para {ip}")))?;
|
||||
info!(%ip, %name, "ResolveAddress");
|
||||
Ok((vec![(0, name)], 0))
|
||||
}
|
||||
|
||||
async fn resolve_record(
|
||||
&self,
|
||||
_ifindex: i32,
|
||||
_name: String,
|
||||
_class: u16,
|
||||
_type_: u16,
|
||||
_flags: u64,
|
||||
) -> fdo::Result<(Vec<(i32, u16, u16, Vec<u8>)>, u64)> {
|
||||
Err(fdo::Error::NotSupported(
|
||||
"ResolveRecord requiere acceso DNS directo — stub no implementado".into()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_address(family: i32, bytes: &[u8]) -> Option<IpAddr> {
|
||||
match family {
|
||||
AF_INET if bytes.len() == 4 => {
|
||||
let mut a = [0u8; 4];
|
||||
a.copy_from_slice(bytes);
|
||||
Some(IpAddr::V4(std::net::Ipv4Addr::from(a)))
|
||||
}
|
||||
AF_INET6 if bytes.len() == 16 => {
|
||||
let mut a = [0u8; 16];
|
||||
a.copy_from_slice(bytes);
|
||||
Some(IpAddr::V6(std::net::Ipv6Addr::from(a)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// getnameinfo(3) wrapper. Devuelve None si no resuelve.
|
||||
fn reverse_lookup(ip: IpAddr) -> Option<String> {
|
||||
use std::os::raw::c_char;
|
||||
let mut buf = [0i8; 256];
|
||||
let r = match ip {
|
||||
IpAddr::V4(v4) => unsafe {
|
||||
let octets = v4.octets();
|
||||
let mut sin = std::mem::zeroed::<libc::sockaddr_in>();
|
||||
sin.sin_family = libc::AF_INET as u16;
|
||||
sin.sin_addr = libc::in_addr {
|
||||
s_addr: u32::from_ne_bytes(octets),
|
||||
};
|
||||
libc::getnameinfo(
|
||||
&sin as *const _ as *const libc::sockaddr,
|
||||
std::mem::size_of::<libc::sockaddr_in>() as u32,
|
||||
buf.as_mut_ptr() as *mut c_char, buf.len() as u32,
|
||||
std::ptr::null_mut(), 0,
|
||||
libc::NI_NAMEREQD,
|
||||
)
|
||||
},
|
||||
IpAddr::V6(v6) => unsafe {
|
||||
let octets = v6.octets();
|
||||
let mut sin6 = std::mem::zeroed::<libc::sockaddr_in6>();
|
||||
sin6.sin6_family = libc::AF_INET6 as u16;
|
||||
sin6.sin6_addr.s6_addr.copy_from_slice(&octets);
|
||||
libc::getnameinfo(
|
||||
&sin6 as *const _ as *const libc::sockaddr,
|
||||
std::mem::size_of::<libc::sockaddr_in6>() as u32,
|
||||
buf.as_mut_ptr() as *mut c_char, buf.len() as u32,
|
||||
std::ptr::null_mut(), 0,
|
||||
libc::NI_NAMEREQD,
|
||||
)
|
||||
},
|
||||
};
|
||||
if r != 0 { return None; }
|
||||
let cs = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) };
|
||||
cs.to_str().ok().map(String::from)
|
||||
}
|
||||
|
||||
extern crate libc;
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa3; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_resolved_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "ente-snapshot"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Persistencia del fractal. Captura el estado live (Cards encarnadas con
|
||||
//! sus identidades preservadas) a un blob JSON. Al restaurar, las mismas
|
||||
//! Ulids vuelven a la vida — los PIDs cambian (kernel no los preserva) pero
|
||||
//! el grafo se reconstruye con la misma topología.
|
||||
//!
|
||||
//! Lo que NO se persiste:
|
||||
//! - PIDs (irrelevantes tras reboot)
|
||||
//! - bus_connections (runtime-only)
|
||||
//! - pending_invokes (en vuelo, se descartan)
|
||||
//! - device presence (uevents reconstruyen el índice)
|
||||
|
||||
use ente_card::EntityCard;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use ulid::Ulid;
|
||||
|
||||
pub const SNAPSHOT_VERSION: u16 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FractalSnapshot {
|
||||
pub version: u16,
|
||||
pub timestamp_ms: u64,
|
||||
pub seed_id: Ulid,
|
||||
pub seed_label: String,
|
||||
/// Cards live al momento del checkpoint, excluyendo la Semilla.
|
||||
/// Al restaurar se inyectan en `genesis` con sus Ulids originales.
|
||||
pub entes: Vec<EntityCard>,
|
||||
}
|
||||
|
||||
impl FractalSnapshot {
|
||||
pub fn write(&self, path: &Path) -> anyhow::Result<()> {
|
||||
let bytes = serde_json::to_vec_pretty(self)?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
// Escritura atómica: temp file + rename.
|
||||
let tmp = path.with_extension("tmp");
|
||||
std::fs::write(&tmp, &bytes)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn read(path: &Path) -> anyhow::Result<Self> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
let snap: FractalSnapshot = serde_json::from_slice(&bytes)?;
|
||||
if snap.version != SNAPSHOT_VERSION {
|
||||
anyhow::bail!(
|
||||
"snapshot version {} no soportada (esperada {})",
|
||||
snap.version, SNAPSHOT_VERSION
|
||||
);
|
||||
}
|
||||
Ok(snap)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "ente-soma"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Encarnación del Soma: traducción de SomaSpec a syscalls.
|
||||
//!
|
||||
//! Esta capa es la única parte de PID 1 que toca syscalls de namespacing —
|
||||
//! todo lo demás opera sobre tipos de alto nivel. La complejidad vive aquí
|
||||
//! por diseño: encapsulada, auditable, y con un único punto de entrada.
|
||||
//!
|
||||
//! ## Protocolo padre↔hijo en el path namespaced
|
||||
//!
|
||||
//! ```text
|
||||
//! parent child
|
||||
//! | |
|
||||
//! |--- clone() ------->| (child empieza dentro de los nuevos NS)
|
||||
//! | |
|
||||
//! | |---- read(sync_r, 1) ---- (bloquea)
|
||||
//! | |
|
||||
//! | write uid_map |
|
||||
//! | write gid_map |
|
||||
//! | cgroup move |
|
||||
//! | cpu affinity |
|
||||
//! | |
|
||||
//! |--- write(sync_w) ->|
|
||||
//! | |---- setrlimit
|
||||
//! | |---- mount(/, MS_PRIVATE | MS_REC)
|
||||
//! | |---- execve()
|
||||
//! ```
|
||||
|
||||
use ente_card::{CgroupSpec, EntityCard, NamespaceSet, Payload, ResourceLimits};
|
||||
use nix::fcntl::OFlag;
|
||||
use nix::sched::CloneFlags;
|
||||
use nix::unistd::{pipe2, Pid};
|
||||
use std::ffi::CString;
|
||||
use std::os::fd::{AsRawFd, IntoRawFd, RawFd};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use tracing::{info, warn};
|
||||
|
||||
/// Path del socket del bus interno. Se establece una sola vez al arrancar
|
||||
/// PID 1 (después de que el listener bind exitoso). Cada hijo encarnado
|
||||
/// recibe este path en `ENTE_BUS_SOCK`.
|
||||
static BUS_SOCK_PATH: OnceLock<String> = OnceLock::new();
|
||||
|
||||
pub fn set_bus_sock(path: String) {
|
||||
let _ = BUS_SOCK_PATH.set(path);
|
||||
}
|
||||
|
||||
fn build_env(card: &EntityCard, base_envp: &[(String, String)]) -> Vec<(String, String)> {
|
||||
// Heredamos parent env, sobreescribimos con el envp explícito de la Card,
|
||||
// y al final inyectamos las vars del fractal (no negociables).
|
||||
let mut env: Vec<(String, String)> = std::env::vars().collect();
|
||||
for (k, v) in base_envp {
|
||||
env.retain(|(ek, _)| ek != k);
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
if let Some(p) = BUS_SOCK_PATH.get() {
|
||||
env.retain(|(k, _)| k != ente_bus::ENV_BUS_SOCK);
|
||||
env.push((ente_bus::ENV_BUS_SOCK.into(), p.clone()));
|
||||
}
|
||||
env.retain(|(k, _)| k != ente_bus::ENV_ENTE_ID);
|
||||
env.push((ente_bus::ENV_ENTE_ID.into(), card.id.to_string()));
|
||||
// Apps `Type=notify` (sd_notify) leen NOTIFY_SOCKET. Apuntamos al path
|
||||
// canónico de systemd; si ente-notify-compat no está corriendo, apps
|
||||
// sólo verán que sd_notify falla y siguen sin "ready" signal — no es fatal.
|
||||
env.retain(|(k, _)| k != "NOTIFY_SOCKET");
|
||||
env.push(("NOTIFY_SOCKET".into(), "/run/systemd/notify".into()));
|
||||
env
|
||||
}
|
||||
|
||||
pub fn incarnate(card: &EntityCard) -> anyhow::Result<Pid> {
|
||||
if needs_namespacing(&card.soma.namespaces) {
|
||||
incarnate_namespaced(card)
|
||||
} else {
|
||||
incarnate_plain(card)
|
||||
}
|
||||
}
|
||||
|
||||
fn needs_namespacing(ns: &NamespaceSet) -> bool {
|
||||
ns.mount || ns.pid || ns.net || ns.uts || ns.ipc || ns.user || ns.cgroup
|
||||
}
|
||||
|
||||
/// Path simple: para Entes que no requieren aislamiento. Útil para Entes-shim
|
||||
/// que conviven con el host (e.g. compat-logind) y para dev mode.
|
||||
fn incarnate_plain(card: &EntityCard) -> anyhow::Result<Pid> {
|
||||
let (exec, argv, base_envp) = match &card.payload {
|
||||
Payload::Native { exec, argv, envp } => (exec.clone(), argv.clone(), envp.clone()),
|
||||
Payload::Legacy { exec, argv, .. } => (exec.clone(), argv.clone(), Vec::new()),
|
||||
_ => anyhow::bail!("incarnate_plain: payload no ejecutable"),
|
||||
};
|
||||
let env = build_env(card, &base_envp);
|
||||
let mut cmd = Command::new(&exec);
|
||||
cmd.args(&argv);
|
||||
cmd.env_clear();
|
||||
for (k, v) in &env {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
let child = cmd.spawn().map_err(|e| anyhow::anyhow!("spawn {exec}: {e}"))?;
|
||||
Ok(Pid::from_raw(child.id() as i32))
|
||||
}
|
||||
|
||||
/// Path namespaced: clone(2) + sync pipe + setup post-clone en padre + finalize en hijo.
|
||||
fn incarnate_namespaced(card: &EntityCard) -> anyhow::Result<Pid> {
|
||||
let flags = build_clone_flags(&card.soma.namespaces);
|
||||
info!(label = %card.label, ?flags, "namespaced incarnation");
|
||||
|
||||
let (exec, argv, base_envp) = match &card.payload {
|
||||
Payload::Native { exec, argv, envp } => (exec.clone(), argv.clone(), envp.clone()),
|
||||
Payload::Legacy { exec, argv, .. } => (exec.clone(), argv.clone(), Vec::new()),
|
||||
_ => anyhow::bail!("incarnate_namespaced: payload no ejecutable"),
|
||||
};
|
||||
|
||||
// Pipe O_CLOEXEC: el read del lado hijo es lo que hace race-free el setup.
|
||||
// O_CLOEXEC garantiza que el fd se cierra automáticamente en execve, así
|
||||
// no contamina el binario final.
|
||||
let (sync_r, sync_w) = pipe2(OFlag::O_CLOEXEC)?;
|
||||
let sync_r_raw: RawFd = sync_r.into_raw_fd();
|
||||
let sync_w_raw: RawFd = sync_w.into_raw_fd();
|
||||
|
||||
let exec_c = CString::new(exec.clone())?;
|
||||
let argv_c: Vec<CString> = std::iter::once(exec_c.clone())
|
||||
.chain(argv.iter().filter_map(|s| CString::new(s.as_str()).ok()))
|
||||
.collect();
|
||||
let argv_ptrs: Vec<*const libc::c_char> = argv_c.iter()
|
||||
.map(|c| c.as_ptr())
|
||||
.chain(std::iter::once(std::ptr::null()))
|
||||
.collect();
|
||||
|
||||
// envp construido pre-clone: padre y hijo comparten el COW. Tras execve
|
||||
// el kernel reemplaza el address space, así que las CStrings sólo viven
|
||||
// hasta el syscall.
|
||||
let env_pairs = build_env(card, &base_envp);
|
||||
let envp_c: Vec<CString> = env_pairs.iter()
|
||||
.filter_map(|(k, v)| CString::new(format!("{k}={v}")).ok())
|
||||
.collect();
|
||||
let envp_ptrs: Vec<*const libc::c_char> = envp_c.iter()
|
||||
.map(|c| c.as_ptr())
|
||||
.chain(std::iter::once(std::ptr::null()))
|
||||
.collect();
|
||||
|
||||
let rlimits = card.soma.rlimits.clone();
|
||||
let mount_ns_enabled = card.soma.namespaces.mount;
|
||||
|
||||
// SAFETY: la clausura corre en stack nuevo dentro de un proceso recién
|
||||
// clonado, COW del padre. Reglas inviolables:
|
||||
// - sólo syscalls async-signal-safe
|
||||
// - no `println!`/`tracing!`/cualquier I/O del runtime
|
||||
// - no allocator (vec/box/string)
|
||||
// - no Drop con efectos
|
||||
// - capturar sólo Copy o datos pre-construidos
|
||||
let cb = Box::new(move || -> isize {
|
||||
// 1) Cerrar el extremo de escritura: pertenece al padre.
|
||||
unsafe { libc::close(sync_w_raw); }
|
||||
|
||||
// 2) Bloquear hasta que el padre termine el setup (uid_map, cgroup, etc).
|
||||
let mut byte = [0u8; 1];
|
||||
let n = unsafe {
|
||||
libc::read(sync_r_raw, byte.as_mut_ptr() as *mut _, 1)
|
||||
};
|
||||
if n != 1 { unsafe { libc::_exit(101); } }
|
||||
unsafe { libc::close(sync_r_raw); }
|
||||
|
||||
// 3) Aplicar rlimits dentro del nuevo namespace.
|
||||
unsafe { apply_rlimits_unchecked(&rlimits); }
|
||||
|
||||
// 4) Si tenemos mount ns, marcar / como privado recursivamente para
|
||||
// que mounts del Ente no se filtren al host (es la trampa más
|
||||
// típica al delegar mount ns).
|
||||
if mount_ns_enabled {
|
||||
unsafe {
|
||||
libc::mount(
|
||||
std::ptr::null(),
|
||||
b"/\0".as_ptr() as *const _,
|
||||
std::ptr::null(),
|
||||
libc::MS_PRIVATE | libc::MS_REC,
|
||||
std::ptr::null(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 5) execve. Si retorna, falló.
|
||||
unsafe {
|
||||
libc::execve(exec_c.as_ptr(), argv_ptrs.as_ptr(), envp_ptrs.as_ptr());
|
||||
libc::_exit(102);
|
||||
}
|
||||
});
|
||||
|
||||
let mut stack = vec![0u8; 1024 * 1024];
|
||||
|
||||
#[allow(deprecated)]
|
||||
let pid = unsafe {
|
||||
nix::sched::clone(cb, &mut stack, flags, Some(libc::SIGCHLD))
|
||||
}.map_err(|e| {
|
||||
unsafe { libc::close(sync_r_raw); libc::close(sync_w_raw); }
|
||||
anyhow::anyhow!("clone failed: {e}")
|
||||
})?;
|
||||
|
||||
// Padre: cerrar el extremo de lectura.
|
||||
unsafe { libc::close(sync_r_raw); }
|
||||
|
||||
// Setup post-clone en padre. Errores aquí no son fatales — registramos y
|
||||
// continuamos. Si algo crítico falla, el hijo execve seguirá adelante con
|
||||
// configuración degradada y el supervisor decidirá qué hacer.
|
||||
if let Err(e) = configure_child(pid, card) {
|
||||
warn!(?e, ?pid, "configure_child errores no-fatales");
|
||||
}
|
||||
|
||||
// Despertar al hijo.
|
||||
let signal_byte = [b'x'];
|
||||
let written = unsafe {
|
||||
libc::write(sync_w_raw, signal_byte.as_ptr() as *const _, 1)
|
||||
};
|
||||
unsafe { libc::close(sync_w_raw); }
|
||||
if written != 1 {
|
||||
warn!(?pid, "no se pudo señalizar al hijo (write devolvió {})", written);
|
||||
}
|
||||
|
||||
if matches!(&card.payload, Payload::Legacy { fakes, .. } if !fakes.is_empty()) {
|
||||
// TODO: facades viven en un Ente-shim aparte que se inyecta vía
|
||||
// bind-mount sobre /run/systemd/notify, /run/dbus/system_bus_socket,
|
||||
// etc. Cuando exista, registrarlas aquí.
|
||||
warn!("legacy facades declaradas pero shim post-clone no implementado");
|
||||
}
|
||||
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
/// Setup que requiere capacidades del padre: uid_map, gid_map, cgroup move.
|
||||
/// Estos archivos en /proc/<pid>/* tienen reglas de propiedad que sólo el
|
||||
/// padre puede satisfacer mientras el hijo está suspendido en el sync pipe.
|
||||
fn configure_child(pid: Pid, card: &EntityCard) -> anyhow::Result<()> {
|
||||
if card.soma.namespaces.user {
|
||||
// Desde kernel 3.19 se debe escribir "deny" a setgroups antes de
|
||||
// poder escribir gid_map sin CAP_SETGID. Ignorar errores: en kernels
|
||||
// antiguos el archivo no existe y no es problema.
|
||||
let _ = std::fs::write(format!("/proc/{}/setgroups", pid.as_raw()), "deny");
|
||||
|
||||
let uid = nix::unistd::getuid().as_raw();
|
||||
let gid = nix::unistd::getgid().as_raw();
|
||||
std::fs::write(
|
||||
format!("/proc/{}/uid_map", pid.as_raw()),
|
||||
format!("0 {uid} 1"),
|
||||
).map_err(|e| anyhow::anyhow!("write uid_map: {e}"))?;
|
||||
std::fs::write(
|
||||
format!("/proc/{}/gid_map", pid.as_raw()),
|
||||
format!("0 {gid} 1"),
|
||||
).map_err(|e| anyhow::anyhow!("write gid_map: {e}"))?;
|
||||
}
|
||||
|
||||
if !card.soma.cgroup.path.is_empty() {
|
||||
match ensure_cgroup(&card.soma.cgroup) {
|
||||
Ok(abs_path) => {
|
||||
let procs = format!("{abs_path}/cgroup.procs");
|
||||
if let Err(e) = std::fs::write(&procs, format!("{}\n", pid.as_raw())) {
|
||||
warn!(?e, path = %procs, "cgroup move falló");
|
||||
}
|
||||
}
|
||||
Err(e) => warn!(?e, path = %card.soma.cgroup.path, "ensure_cgroup falló"),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(cpus) = &card.soma.cpu_affinity {
|
||||
if let Err(e) = set_cpu_affinity(pid, cpus) {
|
||||
warn!(?e, ?pid, "sched_setaffinity falló");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_cpu_affinity(pid: Pid, cpus: &[u32]) -> anyhow::Result<()> {
|
||||
let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() };
|
||||
unsafe { libc::CPU_ZERO(&mut set); }
|
||||
for &c in cpus {
|
||||
unsafe { libc::CPU_SET(c as usize, &mut set); }
|
||||
}
|
||||
let r = unsafe {
|
||||
libc::sched_setaffinity(pid.as_raw(), std::mem::size_of::<libc::cpu_set_t>(), &set)
|
||||
};
|
||||
if r != 0 {
|
||||
anyhow::bail!("sched_setaffinity: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// SAFETY: invocada en el hijo post-clone, sólo libc, no Rust I/O.
|
||||
unsafe fn apply_rlimits_unchecked(rl: &ResourceLimits) {
|
||||
if let Some(mem) = rl.mem_bytes {
|
||||
let lim = libc::rlimit { rlim_cur: mem, rlim_max: mem };
|
||||
libc::setrlimit(libc::RLIMIT_AS, &lim);
|
||||
}
|
||||
if let Some(np) = rl.nproc {
|
||||
let lim = libc::rlimit { rlim_cur: np as u64, rlim_max: np as u64 };
|
||||
libc::setrlimit(libc::RLIMIT_NPROC, &lim);
|
||||
}
|
||||
if let Some(nf) = rl.nofile {
|
||||
let lim = libc::rlimit { rlim_cur: nf as u64, rlim_max: nf as u64 };
|
||||
libc::setrlimit(libc::RLIMIT_NOFILE, &lim);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cgroup actual del proceso PID 1 (o ente-zero en dev). Lo usamos como
|
||||
/// prefijo para paths declarados relativos en CgroupSpec.path. En prod (PID 1
|
||||
/// como child del kernel) será `/`. En dev bajo systemd-user será algo como
|
||||
/// `/user.slice/user-1001.slice/user@1001.service/...`.
|
||||
fn current_cgroup() -> Option<String> {
|
||||
let s = std::fs::read_to_string("/proc/self/cgroup").ok()?;
|
||||
// Formato unified (cgroup v2): "0::/user.slice/..."
|
||||
s.lines()
|
||||
.find_map(|l| l.strip_prefix("0::"))
|
||||
.map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
/// Resuelve un path declarado en CgroupSpec contra la jerarquía real.
|
||||
/// - path absoluto (empieza con `/`): respetar tal cual
|
||||
/// - path relativo: prefijar con cgroup actual de PID 1
|
||||
fn resolve_cgroup_path(spec_path: &str) -> String {
|
||||
if spec_path.is_empty() { return String::new(); }
|
||||
if spec_path.starts_with('/') {
|
||||
return spec_path.to_string();
|
||||
}
|
||||
let trimmed = spec_path.trim_start_matches('/');
|
||||
if let Some(cg) = current_cgroup() {
|
||||
let base = if cg == "/" { String::new() } else { cg.trim_end_matches('/').to_string() };
|
||||
format!("{base}/{trimmed}")
|
||||
} else {
|
||||
format!("/{trimmed}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Crea el cgroup declarado, aplica weights. Devuelve el path absoluto
|
||||
/// resultante bajo /sys/fs/cgroup.
|
||||
fn ensure_cgroup(spec: &CgroupSpec) -> anyhow::Result<String> {
|
||||
let rel = resolve_cgroup_path(&spec.path);
|
||||
if rel.is_empty() {
|
||||
anyhow::bail!("cgroup path vacío");
|
||||
}
|
||||
let abs = format!("/sys/fs/cgroup{}", rel);
|
||||
std::fs::create_dir_all(&abs)
|
||||
.map_err(|e| anyhow::anyhow!("mkdir {}: {e}", abs))?;
|
||||
if let Some(w) = spec.cpu_weight {
|
||||
let _ = std::fs::write(format!("{abs}/cpu.weight"), format!("{w}\n"));
|
||||
}
|
||||
if let Some(w) = spec.io_weight {
|
||||
// io.weight requiere el formato "default <n>" en cgroup v2.
|
||||
let _ = std::fs::write(format!("{abs}/io.weight"), format!("default {w}\n"));
|
||||
}
|
||||
Ok(abs)
|
||||
}
|
||||
|
||||
fn build_clone_flags(ns: &NamespaceSet) -> CloneFlags {
|
||||
let mut f = CloneFlags::empty();
|
||||
if ns.mount { f |= CloneFlags::CLONE_NEWNS; }
|
||||
if ns.pid { f |= CloneFlags::CLONE_NEWPID; }
|
||||
if ns.net { f |= CloneFlags::CLONE_NEWNET; }
|
||||
if ns.uts { f |= CloneFlags::CLONE_NEWUTS; }
|
||||
if ns.ipc { f |= CloneFlags::CLONE_NEWIPC; }
|
||||
if ns.user { f |= CloneFlags::CLONE_NEWUSER; }
|
||||
if ns.cgroup { f |= CloneFlags::CLONE_NEWCGROUP; }
|
||||
f
|
||||
}
|
||||
|
||||
// AsRawFd unused but keep the import alive — soma may grow more fd handling.
|
||||
#[allow(dead_code)]
|
||||
fn _keep_imports(_: &dyn AsRawFd) {}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ente-systemd1-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-systemd1-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,280 @@
|
||||
//! ente-systemd1-compat: shim de `org.freedesktop.systemd1.Manager`.
|
||||
//!
|
||||
//! Centro de control que `systemctl` consulta. Sin esto, `systemctl list-units`
|
||||
//! falla con `Failed to connect to bus` aunque el sistema funcione.
|
||||
//!
|
||||
//! Mapeo: cada Ente vivo del fractal aparece como una "unit" cuyo nombre es
|
||||
//! `<label>.service`. Estados:
|
||||
//! - `loaded` siempre (porque está en el grafo)
|
||||
//! - `active` si tiene PID o es Wasm corriendo, `inactive` si está virtual
|
||||
//! - sub_state: `running`/`exited`/`virtual`
|
||||
//!
|
||||
//! Métodos cubiertos del subset que `systemctl` típicamente llama al boot:
|
||||
//! - ListUnits (basis de `systemctl list-units`)
|
||||
//! - GetUnit / GetUnitByPID (object-path lookup; no servimos métodos del unit)
|
||||
//! - StartUnit / StopUnit / RestartUnit (forwardea al bus interno)
|
||||
//! - Subscribe / Unsubscribe (no-op)
|
||||
//! - Reload (no-op — Cards inmutables)
|
||||
//! - ListUnitFiles (vacío)
|
||||
//! - GetVersion / Environment / Architecture (properties)
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::collections::HashMap;
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface, zvariant::{ObjectPath, OwnedObjectPath, OwnedValue}};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.systemd1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/systemd1";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-systemd1-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = SystemdManager;
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo systemctl");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
|
||||
},
|
||||
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
|
||||
}
|
||||
}
|
||||
|
||||
struct SystemdManager;
|
||||
|
||||
/// Wire format de un unit en `ListUnits`:
|
||||
/// (name, description, load_state, active_state, sub_state, followed,
|
||||
/// unit_path, job_id, job_type, job_path)
|
||||
type UnitInfo = (
|
||||
String, String, String, String, String, String,
|
||||
OwnedObjectPath, u32, String, OwnedObjectPath,
|
||||
);
|
||||
|
||||
#[interface(name = "org.freedesktop.systemd1.Manager")]
|
||||
impl SystemdManager {
|
||||
async fn list_units(&self) -> fdo::Result<Vec<UnitInfo>> {
|
||||
let entes = match query_list_entes().await {
|
||||
Some(es) => es,
|
||||
None => return Ok(vec![]),
|
||||
};
|
||||
let unit_path = ObjectPath::try_from("/org/freedesktop/systemd1/unit/_invalid")
|
||||
.map_err(|e| fdo::Error::Failed(format!("path: {e}")))?;
|
||||
let job_path = ObjectPath::try_from("/")
|
||||
.map_err(|e| fdo::Error::Failed(format!("path: {e}")))?;
|
||||
|
||||
let mut out = Vec::with_capacity(entes.len());
|
||||
for e in entes {
|
||||
let name = format!("{}.service", e.label);
|
||||
let description = format!("Ente: {} ({})", e.label, e.id);
|
||||
let active_state = if e.pid.is_some() { "active" } else { "active" };
|
||||
let sub_state = match e.pid {
|
||||
Some(_) => "running",
|
||||
None => "virtual",
|
||||
};
|
||||
out.push((
|
||||
name,
|
||||
description,
|
||||
"loaded".to_string(),
|
||||
active_state.to_string(),
|
||||
sub_state.to_string(),
|
||||
String::new(), // followed_unit
|
||||
unit_path.clone().into(),
|
||||
0u32, // job_id
|
||||
String::new(), // job_type
|
||||
job_path.clone().into(),
|
||||
));
|
||||
}
|
||||
info!(count = out.len(), "ListUnits");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn list_units_filtered(&self, _states: Vec<String>) -> fdo::Result<Vec<UnitInfo>> {
|
||||
// Subset simple: ignoramos el filtro y devolvemos todas.
|
||||
self.list_units().await
|
||||
}
|
||||
|
||||
async fn list_units_by_names(&self, names: Vec<String>) -> fdo::Result<Vec<UnitInfo>> {
|
||||
let all = self.list_units().await?;
|
||||
let want: std::collections::HashSet<&String> = names.iter().collect();
|
||||
Ok(all.into_iter().filter(|u| want.contains(&u.0)).collect())
|
||||
}
|
||||
|
||||
async fn get_unit(&self, name: String) -> fdo::Result<OwnedObjectPath> {
|
||||
if let Some(entes) = query_list_entes().await {
|
||||
if entes.iter().any(|e| format!("{}.service", e.label) == name) {
|
||||
let path = format!("/org/freedesktop/systemd1/unit/{}", escape_unit_name(&name));
|
||||
return ObjectPath::try_from(path)
|
||||
.map(OwnedObjectPath::from)
|
||||
.map_err(|e| fdo::Error::Failed(format!("path: {e}")));
|
||||
}
|
||||
}
|
||||
Err(fdo::Error::Failed(format!("Unit {name} not found")))
|
||||
}
|
||||
|
||||
async fn get_unit_by_pid(&self, pid: u32) -> fdo::Result<OwnedObjectPath> {
|
||||
if let Some(entes) = query_list_entes().await {
|
||||
if let Some(e) = entes.iter().find(|e| e.pid == Some(pid as i32)) {
|
||||
let path = format!("/org/freedesktop/systemd1/unit/{}",
|
||||
escape_unit_name(&format!("{}.service", e.label)));
|
||||
return ObjectPath::try_from(path)
|
||||
.map(OwnedObjectPath::from)
|
||||
.map_err(|e| fdo::Error::Failed(format!("path: {e}")));
|
||||
}
|
||||
}
|
||||
Err(fdo::Error::Failed(format!("PID {pid} not in any unit")))
|
||||
}
|
||||
|
||||
async fn start_unit(&self, name: String, _mode: String) -> fdo::Result<OwnedObjectPath> {
|
||||
warn!(%name, "StartUnit no implementado — Cards no se 'start' tras boot");
|
||||
Err(fdo::Error::NotSupported(
|
||||
"StartUnit: el fractal usa Cards cargadas al boot, no unit files dinámicos".into()
|
||||
))
|
||||
}
|
||||
|
||||
async fn stop_unit(&self, name: String, _mode: String) -> fdo::Result<OwnedObjectPath> {
|
||||
warn!(%name, "StopUnit (stub: TODO via bus capability)");
|
||||
// TODO: bus → graph → kill PID por label. Por ahora no-op.
|
||||
let path = ObjectPath::try_from("/").unwrap();
|
||||
Ok(path.into())
|
||||
}
|
||||
|
||||
async fn restart_unit(&self, name: String, mode: String) -> fdo::Result<OwnedObjectPath> {
|
||||
info!(%name, "RestartUnit (delega a StopUnit)");
|
||||
self.stop_unit(name, mode).await
|
||||
}
|
||||
|
||||
async fn reload_unit(&self, name: String, _mode: String) -> fdo::Result<OwnedObjectPath> {
|
||||
info!(%name, "ReloadUnit (no-op — Cards inmutables)");
|
||||
let path = ObjectPath::try_from("/").unwrap();
|
||||
Ok(path.into())
|
||||
}
|
||||
|
||||
async fn kill_unit(&self, name: String, _who: String, _signal: i32) -> fdo::Result<()> {
|
||||
warn!(%name, "KillUnit (stub)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn subscribe(&self) -> fdo::Result<()> { Ok(()) }
|
||||
async fn unsubscribe(&self) -> fdo::Result<()> { Ok(()) }
|
||||
|
||||
async fn reload(&self) -> fdo::Result<()> {
|
||||
info!("Reload: trigger re-read (no-op — Cards no se recargan tras boot)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_unit_files(&self) -> fdo::Result<Vec<(String, String)>> {
|
||||
// Empty: no usamos unit files. Cards en su lugar.
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn list_jobs(&self) -> fdo::Result<Vec<(u32, String, String, String, OwnedObjectPath, OwnedObjectPath)>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn get_default_target(&self) -> fdo::Result<String> {
|
||||
Ok("multi-user.target".into())
|
||||
}
|
||||
|
||||
async fn set_default_target(&self, _name: String, _force: bool) -> fdo::Result<(Vec<String>, Vec<String>, Vec<String>)> {
|
||||
Err(fdo::Error::NotSupported("default target gestionado por Card de Semilla".into()))
|
||||
}
|
||||
|
||||
// ----- Properties -----
|
||||
|
||||
#[zbus(property)]
|
||||
async fn version(&self) -> String { format!("ente-systemd1-compat {}", env!("CARGO_PKG_VERSION")) }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn architecture(&self) -> String { std::env::consts::ARCH.into() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn features(&self) -> String { "+ENTE-FRACTAL".into() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn virtualization(&self) -> String { String::new() }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn confined(&self) -> bool { false }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn environment(&self) -> Vec<String> {
|
||||
std::env::vars().map(|(k, v)| format!("{k}={v}")).collect()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn n_names(&self) -> u32 { 0 }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn n_jobs(&self) -> u32 { 0 }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn progress(&self) -> f64 { 1.0 }
|
||||
}
|
||||
|
||||
/// Pregunta al bus interno por la lista de Entes vivos.
|
||||
async fn query_list_entes() -> Option<Vec<ente_bus::EnteInfo>> {
|
||||
let mut client = match BusClient::from_env().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => { warn!(?e, "no bus client — devuelvo vacío"); return None; }
|
||||
};
|
||||
match client.call(BusRequest::ListEntes).await {
|
||||
Ok(BusResponse::Entes(entes)) => Some(entes),
|
||||
Ok(other) => { warn!(?other, "ListEntes respuesta inesperada"); None }
|
||||
Err(e) => { warn!(?e, "ListEntes call falló"); None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape de nombres de units para object paths según convención systemd:
|
||||
/// `.` → `_2e`, `-` → `_2d`, etc. Para el demo usamos un escape simple.
|
||||
fn escape_unit_name(name: &str) -> String {
|
||||
name.chars().map(|c| match c {
|
||||
c if c.is_ascii_alphanumeric() => c.to_string(),
|
||||
c => format!("_{:02x}", c as u32),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa6; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_systemd1_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn _suppress(_: HashMap<String, OwnedValue>) {} // mantener import si se reduce
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ente-timedated-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-timedated-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zbus = { version = "4", default-features = false, features = ["tokio"] }
|
||||
@@ -0,0 +1,182 @@
|
||||
//! ente-timedated-compat: shim de `org.freedesktop.timedate1`.
|
||||
//!
|
||||
//! GNOME settings panel "Date & Time" llama aquí. Properties read-only se
|
||||
//! mapean a syscalls/lecturas del sistema; setters log + forward.
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use zbus::{fdo, interface};
|
||||
|
||||
const BUS_NAME: &str = "org.freedesktop.timedate1";
|
||||
const OBJ_PATH: &str = "/org/freedesktop/timedate1";
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-timedated-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let manager = TimedateManager::default();
|
||||
let conn_result = zbus::connection::Builder::system()
|
||||
.and_then(|b| b.name(BUS_NAME))
|
||||
.and_then(|b| b.serve_at(OBJ_PATH, manager));
|
||||
match conn_result {
|
||||
Ok(builder) => match builder.build().await {
|
||||
Ok(_conn) => {
|
||||
info!(name = BUS_NAME, "name acquired, sirviendo");
|
||||
wait_for_term().await
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "build conn falló — modo idle");
|
||||
wait_for_term().await
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
warn!(?e, "builder D-Bus falló — modo idle");
|
||||
wait_for_term().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TimedateManager;
|
||||
|
||||
#[interface(name = "org.freedesktop.timedate1")]
|
||||
impl TimedateManager {
|
||||
// ----- Properties -----
|
||||
|
||||
/// Timezone configurada. Por defecto leemos el target de /etc/localtime
|
||||
/// (un symlink a /usr/share/zoneinfo/<TZ>).
|
||||
#[zbus(property)]
|
||||
async fn timezone(&self) -> String {
|
||||
std::fs::read_link("/etc/localtime")
|
||||
.ok()
|
||||
.and_then(|p| {
|
||||
let s = p.to_string_lossy().into_owned();
|
||||
s.strip_prefix("/usr/share/zoneinfo/").map(String::from)
|
||||
.or_else(|| s.split("/zoneinfo/").nth(1).map(String::from))
|
||||
})
|
||||
.unwrap_or_else(|| "UTC".into())
|
||||
}
|
||||
|
||||
/// True si el RTC del hardware está en local time. Convención moderna
|
||||
/// es UTC (false). Reportamos false como default.
|
||||
#[zbus(property)]
|
||||
async fn local_rtc(&self) -> bool { false }
|
||||
|
||||
/// Si NTP es soportado. Reportamos true (asumimos systemd-timesyncd
|
||||
/// o chrony están disponibles en el host).
|
||||
#[zbus(property)]
|
||||
async fn can_ntp(&self) -> bool { true }
|
||||
|
||||
/// Si NTP está activo. Sin daemon real bajo nuestro control no podemos
|
||||
/// consultarlo con precisión — false como default seguro.
|
||||
#[zbus(property)]
|
||||
async fn ntp(&self) -> bool { false }
|
||||
|
||||
#[zbus(property)]
|
||||
async fn ntpsynchronized(&self) -> bool { false }
|
||||
|
||||
/// Timestamp actual en microsegundos desde epoch.
|
||||
#[zbus(property)]
|
||||
async fn time_usec(&self) -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_micros() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn rtctime_usec(&self) -> u64 {
|
||||
// El RTC real requiere ioctl a /dev/rtc — usamos system clock como aprox.
|
||||
SystemTime::now().duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_micros() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
// ----- Setters -----
|
||||
|
||||
async fn set_time(&self, usec_utc: i64, _relative: bool, _interactive: bool) -> fdo::Result<()> {
|
||||
info!(usec_utc, "SetTime (stub: requiere CAP_SYS_TIME para aplicar)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_timezone(&self, timezone: String, _interactive: bool) -> fdo::Result<()> {
|
||||
// Validar contra zoneinfo: el archivo destino debe existir.
|
||||
let zoneinfo = format!("/usr/share/zoneinfo/{timezone}");
|
||||
if !std::path::Path::new(&zoneinfo).exists() {
|
||||
return Err(fdo::Error::InvalidArgs(format!("timezone desconocida: {timezone}")));
|
||||
}
|
||||
// Atomic relink: crear localtime.tmp como symlink, rename.
|
||||
let tmp = "/etc/localtime.tmp";
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
if let Err(e) = std::os::unix::fs::symlink(&zoneinfo, tmp) {
|
||||
return Err(fdo::Error::Failed(format!("symlink: {e}")));
|
||||
}
|
||||
if let Err(e) = std::fs::rename(tmp, "/etc/localtime") {
|
||||
return Err(fdo::Error::Failed(format!("rename: {e}")));
|
||||
}
|
||||
info!(%timezone, "SetTimezone → /etc/localtime");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_local_rtc(&self, local_rtc: bool, _fix_system: bool, _interactive: bool) -> fdo::Result<()> {
|
||||
info!(local_rtc, "SetLocalRTC (stub)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_ntp(&self, ntp: bool, _interactive: bool) -> fdo::Result<()> {
|
||||
info!(ntp, "SetNTP (stub: no controlamos timesyncd)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_timezones(&self) -> fdo::Result<Vec<String>> {
|
||||
// Listar /usr/share/zoneinfo recursivamente. Hacemos un best-effort.
|
||||
let mut out = Vec::new();
|
||||
if let Ok(rd) = std::fs::read_dir("/usr/share/zoneinfo") {
|
||||
for entry in rd.flatten() {
|
||||
if let Ok(name) = entry.file_name().into_string() {
|
||||
if !name.starts_with(|c: char| c.is_lowercase()) && name != "posix" && name != "right" {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa1; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_term() -> anyhow::Result<()> {
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
tokio::select! {
|
||||
_ = term.recv() => info!("SIGTERM"),
|
||||
_ = int_.recv() => info!("SIGINT"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_timedated_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "ente-timer-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-timer-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,228 @@
|
||||
//! ente-timer-compat: scheduler estilo cron + systemd .timer.
|
||||
//!
|
||||
//! Lee config en JSON desde `/etc/ente/timers.json` (override env
|
||||
//! `ENTE_TIMERS_FILE`):
|
||||
//!
|
||||
//! ```json
|
||||
//! [
|
||||
//! {
|
||||
//! "name": "daily-cleanup",
|
||||
//! "schedule": "0 4 * * *",
|
||||
//! "card": {
|
||||
//! "id": "01KQ_TIMER_CLEANUP_0000000",
|
||||
//! "label": "daily-cleanup-job",
|
||||
//! "schema_version": 1,
|
||||
//! "soma": {"namespaces": {}, "rlimits": {}, "cgroup": {"path": ""}},
|
||||
//! "payload": {"Native": {"exec": "/usr/local/bin/cleanup", "argv": [], "envp": []}},
|
||||
//! "supervision": "OneShot",
|
||||
//! "provides": [], "requires": []
|
||||
//! }
|
||||
//! }
|
||||
//! ]
|
||||
//! ```
|
||||
//!
|
||||
//! Schedule: cron 5-fields `min hour dom mon dow` (DOM/DOW como en cron
|
||||
//! tradicional). `*` y `*/N` soportados, listas no.
|
||||
//!
|
||||
//! Cuando un timer dispara, se envía un `BusRequest::Invoke` al bus interno
|
||||
//! con la cap "TimerFire" + payload = serialized Card. Un Ente que provea
|
||||
//! esa cap (futuro: ente-zero internamente) hace el spawn.
|
||||
//!
|
||||
//! Para el demo: log "FIRE" cada vez que el schedule matchea, sin spawn real
|
||||
//! (requiere mover SpawnRequest al protocolo del bus, fuera de scope).
|
||||
|
||||
use ente_bus::{BusClient, BusRequest, BusResponse};
|
||||
use ente_card::Capability;
|
||||
use serde::Deserialize;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct TimerConfig {
|
||||
name: String,
|
||||
/// Cron 5-field: `min hour dom mon dow`. `*`, `N`, `*/N` soportados.
|
||||
schedule: String,
|
||||
/// Card a disparar. Por ahora se loguea — futuro: SpawnRequest via bus.
|
||||
#[serde(default)]
|
||||
card: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Cron {
|
||||
min: CronField,
|
||||
hour: CronField,
|
||||
dom: CronField,
|
||||
mon: CronField,
|
||||
dow: CronField,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum CronField {
|
||||
Any,
|
||||
Exact(u32),
|
||||
Step(u32), // */N
|
||||
}
|
||||
|
||||
impl CronField {
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
if s == "*" { return Some(CronField::Any); }
|
||||
if let Some(n) = s.strip_prefix("*/") {
|
||||
return n.parse().ok().map(CronField::Step);
|
||||
}
|
||||
s.parse().ok().map(CronField::Exact)
|
||||
}
|
||||
fn matches(&self, v: u32) -> bool {
|
||||
match self {
|
||||
CronField::Any => true,
|
||||
CronField::Exact(n) => *n == v,
|
||||
CronField::Step(n) if *n > 0 => v % n == 0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Cron {
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
let parts: Vec<&str> = s.split_whitespace().collect();
|
||||
if parts.len() != 5 { return None; }
|
||||
Some(Self {
|
||||
min: CronField::parse(parts[0])?,
|
||||
hour: CronField::parse(parts[1])?,
|
||||
dom: CronField::parse(parts[2])?,
|
||||
mon: CronField::parse(parts[3])?,
|
||||
dow: CronField::parse(parts[4])?,
|
||||
})
|
||||
}
|
||||
fn matches(&self, t: &TimeBits) -> bool {
|
||||
self.min.matches(t.min)
|
||||
&& self.hour.matches(t.hour)
|
||||
&& self.dom.matches(t.dom)
|
||||
&& self.mon.matches(t.mon)
|
||||
&& self.dow.matches(t.dow)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TimeBits {
|
||||
min: u32, hour: u32, dom: u32, mon: u32, dow: u32,
|
||||
}
|
||||
|
||||
/// Decompose epoch_secs en componentes UTC. Algoritmo simple (Howard Hinnant).
|
||||
fn time_bits_utc(epoch_secs: i64) -> TimeBits {
|
||||
let secs_per_day = 86400i64;
|
||||
let days_since_epoch = epoch_secs.div_euclid(secs_per_day);
|
||||
let secs_in_day = epoch_secs.rem_euclid(secs_per_day);
|
||||
let hour = (secs_in_day / 3600) as u32;
|
||||
let min = ((secs_in_day % 3600) / 60) as u32;
|
||||
|
||||
// dow: 1970-01-01 fue jueves (4); cron usa 0-6 con 0=domingo.
|
||||
let dow = ((days_since_epoch + 4).rem_euclid(7)) as u32;
|
||||
|
||||
// Conversión a y/m/d (Howard Hinnant Civil from days).
|
||||
let z = days_since_epoch + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = (z - era * 146_097) as u64;
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe as i64 + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
|
||||
let _y = y + if m <= 2 { 1 } else { 0 };
|
||||
TimeBits { min, hour, dom: d, mon: m, dow }
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
info!("ente-timer-compat: arrancando");
|
||||
announce_to_fractal().await;
|
||||
|
||||
let timers = load_timers();
|
||||
info!(count = timers.len(), "timers cargados");
|
||||
for t in &timers {
|
||||
info!(name = %t.name, schedule = %t.schedule, "timer activo");
|
||||
}
|
||||
|
||||
let parsed: Vec<(TimerConfig, Cron)> = timers.into_iter()
|
||||
.filter_map(|t| {
|
||||
let cron = Cron::parse(&t.schedule)?;
|
||||
Some((t, cron))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut term = signal(SignalKind::terminate())?;
|
||||
let mut int_ = signal(SignalKind::interrupt())?;
|
||||
let mut tick = tokio::time::interval(std::time::Duration::from_secs(60));
|
||||
// Alinear al próximo minuto entero.
|
||||
let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
|
||||
let to_next_min = 60_000 - (now_ms % 60_000);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(to_next_min)).await;
|
||||
tick.tick().await; // descartar primer tick post-alignment
|
||||
|
||||
info!("scheduler activo (cron 5-field UTC)");
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tick.tick() => {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
||||
let bits = time_bits_utc(now);
|
||||
for (cfg, cron) in &parsed {
|
||||
if cron.matches(&bits) {
|
||||
fire(cfg).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = term.recv() => { info!("SIGTERM"); return Ok(()); }
|
||||
_ = int_.recv() => { info!("SIGINT"); return Ok(()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fire(cfg: &TimerConfig) {
|
||||
info!(name = %cfg.name, "TIMER FIRE");
|
||||
if cfg.card.is_none() {
|
||||
return;
|
||||
}
|
||||
// En el futuro: forwardear via bus a un proveedor que haga SpawnRequest.
|
||||
// Por ahora log estructurado.
|
||||
info!(name = %cfg.name, "card spawn requested (no-op por ahora)");
|
||||
}
|
||||
|
||||
fn load_timers() -> Vec<TimerConfig> {
|
||||
let path = std::env::var("ENTE_TIMERS_FILE")
|
||||
.unwrap_or_else(|_| "/etc/ente/timers.json".into());
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(content) => serde_json::from_str(&content).unwrap_or_else(|e| {
|
||||
warn!(?e, path, "timers.json inválido — sin timers");
|
||||
vec![]
|
||||
}),
|
||||
Err(_) => {
|
||||
info!(path, "timers.json ausente — scheduler inactivo");
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn announce_to_fractal() {
|
||||
if let Ok(mut client) = BusClient::from_env().await {
|
||||
let req = BusRequest::Announce {
|
||||
capabilities: vec![Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xa8; 16]),
|
||||
version: 1,
|
||||
}],
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
|
||||
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Announce falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_timer_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "ente-tmpfiles-compat"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-tmpfiles-compat"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,281 @@
|
||||
//! ente-tmpfiles-compat: aplica directivas tmpfiles.d al boot.
|
||||
//!
|
||||
//! Lee, en orden, los conf files de:
|
||||
//! /usr/lib/tmpfiles.d/*.conf
|
||||
//! /etc/tmpfiles.d/*.conf (override del usuario, gana)
|
||||
//! /run/tmpfiles.d/*.conf (efímero)
|
||||
//!
|
||||
//! Aplica un subset de directivas — las suficientes para el boot:
|
||||
//! d — crear directorio (idempotente: no falla si existe)
|
||||
//! D — crear directorio + limpiar contenido si existe
|
||||
//! f — crear archivo (vacío, perms aplicados)
|
||||
//! L — crear symlink (overrideable con `+L` si existe)
|
||||
//! r — remove file (no falla si ausente)
|
||||
//! R — remove recursivamente
|
||||
//! e — adjust perms si existe
|
||||
//!
|
||||
//! Edad/cleanup (`age` field) y modos exotic (b, c, p, P) se ignoran.
|
||||
//! El proceso es OneShot: corre, aplica, sale con código 0 / 1.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tracing::{debug, info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const SEARCH_DIRS: &[&str] = &[
|
||||
"/usr/lib/tmpfiles.d",
|
||||
"/etc/tmpfiles.d",
|
||||
"/run/tmpfiles.d",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Directive {
|
||||
typ: char, // d, D, f, L, r, R, e
|
||||
path: PathBuf,
|
||||
mode: Option<u32>,
|
||||
user: Option<String>,
|
||||
group: Option<String>,
|
||||
arg: Option<String>, // symlink target o content
|
||||
}
|
||||
|
||||
fn main() {
|
||||
init_tracing();
|
||||
info!("ente-tmpfiles-compat: aplicando directivas tmpfiles.d");
|
||||
let directives = collect_directives();
|
||||
info!(count = directives.len(), "directivas a aplicar");
|
||||
|
||||
let mut applied = 0;
|
||||
let mut skipped = 0;
|
||||
let mut errors = 0;
|
||||
for d in directives {
|
||||
match apply(&d) {
|
||||
Ok(true) => applied += 1,
|
||||
Ok(false) => skipped += 1,
|
||||
Err(e) => {
|
||||
warn!(?e, ?d.typ, path = %d.path.display(), "directiva falló");
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
info!(applied, skipped, errors, "tmpfiles aplicado");
|
||||
if errors > 0 { std::process::exit(1); }
|
||||
}
|
||||
|
||||
fn collect_directives() -> Vec<Directive> {
|
||||
// Last-wins por path: /etc supera /usr/lib, /run supera /etc.
|
||||
let mut by_path: BTreeMap<(PathBuf, char), Directive> = BTreeMap::new();
|
||||
for dir in SEARCH_DIRS {
|
||||
if !Path::new(dir).exists() { continue; }
|
||||
let mut entries: Vec<_> = match fs::read_dir(dir) {
|
||||
Ok(rd) => rd.filter_map(|e| e.ok()).collect(),
|
||||
Err(_) => continue,
|
||||
};
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if path.extension().map(|e| e != "conf").unwrap_or(true) { continue; }
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(content) => {
|
||||
for (line_no, line) in content.lines().enumerate() {
|
||||
if let Some(d) = parse_line(line) {
|
||||
by_path.insert((d.path.clone(), d.typ), d);
|
||||
} else if !line.trim().is_empty() && !line.trim().starts_with('#') {
|
||||
debug!(file = %path.display(), line_no, line, "no parseable, skip");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => warn!(?e, path = %path.display(), "read"),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Orden de aplicación: removes (r/R) primero, luego creates (d/D/f/L),
|
||||
// adjusts (e) al final.
|
||||
let mut all: Vec<Directive> = by_path.into_values().collect();
|
||||
all.sort_by_key(|d| match d.typ {
|
||||
'r' | 'R' => 0,
|
||||
'd' | 'D' | 'f' | 'L' => 1,
|
||||
'e' => 2,
|
||||
_ => 3,
|
||||
});
|
||||
all
|
||||
}
|
||||
|
||||
fn parse_line(line: &str) -> Option<Directive> {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') { return None; }
|
||||
// Formato: TYPE PATH MODE USER GROUP AGE ARGUMENT
|
||||
// Strip leading '+' (override marker) y '!' (boot-only) — los soportamos
|
||||
// implícitamente.
|
||||
let typ_str = line.chars().next()?;
|
||||
let typ = match typ_str {
|
||||
'+' | '!' => line.chars().nth(1)?,
|
||||
c => c,
|
||||
};
|
||||
if !"dDfLrRe".contains(typ) { return None; }
|
||||
// tokenize tomando en cuenta '-' como "default"
|
||||
let mut parts = line.splitn(7, char::is_whitespace).filter(|s| !s.is_empty());
|
||||
let _t = parts.next()?;
|
||||
let path = parts.next()?.to_string();
|
||||
let mode = parts.next().and_then(parse_mode);
|
||||
let user = parts.next().and_then(parse_default);
|
||||
let group = parts.next().and_then(parse_default);
|
||||
let _age = parts.next();
|
||||
let arg = parts.next().and_then(parse_default);
|
||||
Some(Directive {
|
||||
typ,
|
||||
path: PathBuf::from(path),
|
||||
mode, user, group, arg,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_default(s: &str) -> Option<String> {
|
||||
if s == "-" { None } else { Some(s.to_string()) }
|
||||
}
|
||||
|
||||
fn parse_mode(s: &str) -> Option<u32> {
|
||||
if s == "-" { return None; }
|
||||
u32::from_str_radix(s.trim_start_matches('~'), 8).ok()
|
||||
}
|
||||
|
||||
fn apply(d: &Directive) -> anyhow::Result<bool> {
|
||||
match d.typ {
|
||||
'd' | 'D' => apply_d(d),
|
||||
'f' => apply_f(d),
|
||||
'L' => apply_l(d),
|
||||
'r' => apply_r(d, false),
|
||||
'R' => apply_r(d, true),
|
||||
'e' => apply_e(d),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_d(d: &Directive) -> anyhow::Result<bool> {
|
||||
fs::create_dir_all(&d.path)
|
||||
.map_err(|e| anyhow::anyhow!("mkdir {}: {e}", d.path.display()))?;
|
||||
if let Some(mode) = d.mode {
|
||||
fs::set_permissions(&d.path, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
chown(&d.path, d.user.as_deref(), d.group.as_deref())?;
|
||||
if d.typ == 'D' {
|
||||
// Limpiar contenido (no recursivo).
|
||||
if let Ok(rd) = fs::read_dir(&d.path) {
|
||||
for entry in rd.flatten() {
|
||||
let p = entry.path();
|
||||
if p.is_dir() { let _ = fs::remove_dir_all(&p); }
|
||||
else { let _ = fs::remove_file(&p); }
|
||||
}
|
||||
}
|
||||
}
|
||||
info!(path = %d.path.display(), mode = ?d.mode, "d/D aplicado");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_f(d: &Directive) -> anyhow::Result<bool> {
|
||||
if !d.path.exists() {
|
||||
if let Some(parent) = d.path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
let content = d.arg.clone().unwrap_or_default();
|
||||
fs::write(&d.path, content.as_bytes())?;
|
||||
}
|
||||
if let Some(mode) = d.mode {
|
||||
fs::set_permissions(&d.path, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
chown(&d.path, d.user.as_deref(), d.group.as_deref())?;
|
||||
info!(path = %d.path.display(), mode = ?d.mode, "f aplicado");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_l(d: &Directive) -> anyhow::Result<bool> {
|
||||
let target = match &d.arg {
|
||||
Some(t) => t,
|
||||
None => anyhow::bail!("L sin target en {}", d.path.display()),
|
||||
};
|
||||
if d.path.exists() {
|
||||
// No sobreescribimos symlinks/files existentes (modo no-`+`).
|
||||
debug!(path = %d.path.display(), "L: existe, skip");
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(parent) = d.path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
std::os::unix::fs::symlink(target, &d.path)?;
|
||||
info!(path = %d.path.display(), %target, "L aplicado");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_r(d: &Directive, recursive: bool) -> anyhow::Result<bool> {
|
||||
if !d.path.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
if recursive {
|
||||
fs::remove_dir_all(&d.path)?;
|
||||
} else if d.path.is_dir() {
|
||||
fs::remove_dir(&d.path)?;
|
||||
} else {
|
||||
fs::remove_file(&d.path)?;
|
||||
}
|
||||
info!(path = %d.path.display(), recursive, "remove aplicado");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_e(d: &Directive) -> anyhow::Result<bool> {
|
||||
if !d.path.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(mode) = d.mode {
|
||||
fs::set_permissions(&d.path, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
chown(&d.path, d.user.as_deref(), d.group.as_deref())?;
|
||||
info!(path = %d.path.display(), "e aplicado");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn chown(path: &Path, user: Option<&str>, group: Option<&str>) -> anyhow::Result<()> {
|
||||
use std::ffi::CString;
|
||||
let uid = match user {
|
||||
Some(u) => Some(lookup_uid(u)?),
|
||||
None => None,
|
||||
};
|
||||
let gid = match group {
|
||||
Some(g) => Some(lookup_gid(g)?),
|
||||
None => None,
|
||||
};
|
||||
let (uid, gid) = (uid.unwrap_or(u32::MAX), gid.unwrap_or(u32::MAX));
|
||||
let cstr = CString::new(path.as_os_str().as_encoded_bytes())?;
|
||||
let r = unsafe { libc::chown(cstr.as_ptr(), uid, gid) };
|
||||
if r != 0 {
|
||||
let e = std::io::Error::last_os_error();
|
||||
// No-op si ya somos non-root y el chown falla con EPERM.
|
||||
if e.raw_os_error() == Some(libc::EPERM) {
|
||||
debug!(path = %path.display(), "chown EPERM (esperado sin root)");
|
||||
return Ok(());
|
||||
}
|
||||
return Err(anyhow::anyhow!("chown: {e}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lookup_uid(name: &str) -> anyhow::Result<u32> {
|
||||
if let Ok(n) = name.parse::<u32>() { return Ok(n); }
|
||||
let cstr = std::ffi::CString::new(name)?;
|
||||
let pw = unsafe { libc::getpwnam(cstr.as_ptr()) };
|
||||
if pw.is_null() { anyhow::bail!("user '{name}' no encontrado"); }
|
||||
Ok(unsafe { (*pw).pw_uid })
|
||||
}
|
||||
|
||||
fn lookup_gid(name: &str) -> anyhow::Result<u32> {
|
||||
if let Ok(n) = name.parse::<u32>() { return Ok(n); }
|
||||
let cstr = std::ffi::CString::new(name)?;
|
||||
let gr = unsafe { libc::getgrnam(cstr.as_ptr()) };
|
||||
if gr.is_null() { anyhow::bail!("group '{name}' no encontrado"); }
|
||||
Ok(unsafe { (*gr).gr_gid })
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_tmpfiles_compat=info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "ente-wasm"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ente-card = { path = "../ente-card" }
|
||||
wasmi = { workspace = true }
|
||||
wat = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Encarnación de Payload::Wasm vía wasmi.
|
||||
//!
|
||||
//! Cada Ente Wasm corre en un hilo dedicado (wasmi es síncrono) que se
|
||||
//! comunica con el grafo vía un identificador propio. El thread::JoinHandle
|
||||
//! se descarta — el ciclo de vida del Wasm se controla por su `entry`
|
||||
//! function: cuando retorna, el Ente se considera disuelto.
|
||||
//!
|
||||
//! ## Host imports expuestos
|
||||
//! - `ente.log(ptr: i32, len: i32)` imprime una string UTF-8
|
||||
//! - `ente.exit(code: i32)` solicita salida del Ente
|
||||
//!
|
||||
//! Más adelante: `ente.bus_call`, `ente.cap_invoke`, etc.
|
||||
|
||||
use ente_card::EntityCard;
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tracing::{error, info, warn};
|
||||
use wasmi::{Caller, Engine, Linker, Memory, Module, Store};
|
||||
|
||||
/// Estado por instancia Wasm. Se accede tanto desde host imports (vía
|
||||
/// `Caller::data()`) como desde el thread runner para estado de salida.
|
||||
pub struct WasmEnte {
|
||||
pub id: ulid::Ulid,
|
||||
pub label: String,
|
||||
pub exit_code: Arc<AtomicI32>,
|
||||
}
|
||||
|
||||
/// Encarna un payload Wasm en un hilo dedicado. Devuelve un identificador
|
||||
/// no-PID que el grafo trata como Ente Virtual con cuerpo de cómputo.
|
||||
pub fn incarnate_wasm(card: &EntityCard, module_bytes: Vec<u8>, entry: String) -> anyhow::Result<()> {
|
||||
let label = card.label.clone();
|
||||
let id = card.id;
|
||||
let exit_code = Arc::new(AtomicI32::new(0));
|
||||
let exit_code_handle = exit_code.clone();
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name(format!("wasm-{label}"))
|
||||
.spawn(move || {
|
||||
if let Err(e) = run_wasm(WasmEnte { id, label: label.clone(), exit_code: exit_code_handle.clone() }, &module_bytes, &entry) {
|
||||
error!(?e, %label, "Wasm ente terminó con error");
|
||||
exit_code_handle.store(-1, Ordering::Relaxed);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_wasm(ente: WasmEnte, module_bytes: &[u8], entry: &str) -> anyhow::Result<()> {
|
||||
let engine = Engine::default();
|
||||
let module = Module::new(&engine, module_bytes)
|
||||
.map_err(|e| anyhow::anyhow!("Wasm module compile: {e}"))?;
|
||||
let mut store = Store::new(&engine, ente);
|
||||
let mut linker = <Linker<WasmEnte>>::new(&engine);
|
||||
|
||||
linker.func_wrap("ente", "log", |caller: Caller<'_, WasmEnte>, ptr: i32, len: i32| {
|
||||
host_log(caller, ptr, len);
|
||||
})?;
|
||||
|
||||
linker.func_wrap("ente", "exit", |mut caller: Caller<'_, WasmEnte>, code: i32| {
|
||||
caller.data_mut().exit_code.store(code, Ordering::Relaxed);
|
||||
})?;
|
||||
|
||||
let pre = linker.instantiate(&mut store, &module)
|
||||
.map_err(|e| anyhow::anyhow!("Wasm instantiate: {e}"))?;
|
||||
let instance = pre.start(&mut store)
|
||||
.map_err(|e| anyhow::anyhow!("Wasm start: {e}"))?;
|
||||
|
||||
let func = instance.get_typed_func::<(), ()>(&store, entry)
|
||||
.map_err(|e| anyhow::anyhow!("Wasm get_func {entry}: {e}"))?;
|
||||
|
||||
info!(label = %store.data().label, %entry, "Wasm ente ejecutando");
|
||||
func.call(&mut store, ()).map_err(|e| anyhow::anyhow!("Wasm call {entry}: {e}"))?;
|
||||
let code = store.data().exit_code.load(Ordering::Relaxed);
|
||||
info!(label = %store.data().label, code, "Wasm ente terminó");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn host_log(caller: Caller<'_, WasmEnte>, ptr: i32, len: i32) {
|
||||
let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
|
||||
Some(m) => m,
|
||||
None => {
|
||||
warn!("Wasm ente sin memoria exportada — log ignorado");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let data = read_memory(&caller, memory, ptr, len);
|
||||
match std::str::from_utf8(&data) {
|
||||
Ok(s) => info!(label = %caller.data().label, "[wasm] {s}"),
|
||||
Err(_) => warn!(label = %caller.data().label, "Wasm log con bytes no UTF-8"),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_memory(caller: &Caller<'_, WasmEnte>, memory: Memory, ptr: i32, len: i32) -> Vec<u8> {
|
||||
let ptr = ptr.max(0) as usize;
|
||||
let len = len.max(0) as usize;
|
||||
let data = memory.data(caller);
|
||||
if ptr.saturating_add(len) > data.len() {
|
||||
return Vec::new();
|
||||
}
|
||||
data[ptr..ptr + len].to_vec()
|
||||
}
|
||||
|
||||
/// Módulo WAT mínimo de demostración. Llama a `ente.log` con "hola fractal".
|
||||
/// Compilado a binario Wasm en runtime con `wat`.
|
||||
pub fn demo_module_bytes() -> anyhow::Result<Vec<u8>> {
|
||||
let wat = r#"
|
||||
(module
|
||||
(import "ente" "log" (func $log (param i32 i32)))
|
||||
(import "ente" "exit" (func $exit (param i32)))
|
||||
(memory (export "memory") 1)
|
||||
(data (i32.const 0) "hola fractal desde wasm")
|
||||
(func (export "_start")
|
||||
(call $log (i32.const 0) (i32.const 23))
|
||||
(call $exit (i32.const 0))
|
||||
)
|
||||
)
|
||||
"#;
|
||||
Ok(wat::parse_str(wat)?)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "ente-zero"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ente-zero"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# Lib crates del fractal — orden: contratos → infra → encarnación → orquestación
|
||||
ente-card = { path = "../ente-card" }
|
||||
ente-bus = { path = "../ente-bus" }
|
||||
ente-cas = { path = "../ente-cas" }
|
||||
ente-kernel = { path = "../ente-kernel" }
|
||||
ente-soma = { path = "../ente-soma" }
|
||||
ente-wasm = { path = "../ente-wasm" }
|
||||
ente-snapshot = { path = "../ente-snapshot" }
|
||||
ente-brain = { path = "../ente-brain" }
|
||||
ente-echo = { path = "../ente-echo" } # solo para constantes del demo
|
||||
|
||||
# Runtime / utilidades de PID 1
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
ulid = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
nix = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Glue entre el bucle primordial y `ente-brain`.
|
||||
//!
|
||||
//! Tres responsabilidades:
|
||||
//! 1. Traducir eventos del grafo (`GraphEvent`) a `ente_brain::EventKind`
|
||||
//! + `SubjectInfo` para el observador y el motor.
|
||||
//! 2. Implementar `ActionSink` para que las Acciones del cerebro tengan
|
||||
//! un canal de salida hacia el grafo (Spawn → SpawnRequest, etc.).
|
||||
//! 3. Encapsular el snapshot de SubjectInfo desde el grafo sin filtrar
|
||||
//! detalles internos al cerebro.
|
||||
|
||||
use crate::events::GraphEvent;
|
||||
use crate::graph::EnteGraph;
|
||||
use ente_brain::{ActionSink, EventKind as BrainEventKind, SubjectInfo};
|
||||
use ente_card::Capability;
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::warn;
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Traduce un GraphEvent a (EventKind, SubjectInfo) para alimentar el cerebro.
|
||||
///
|
||||
/// Devuelve `None` para eventos puramente internos del bus (Response, Close)
|
||||
/// que no son interesantes para reglas o estadística.
|
||||
pub fn graph_event_to_brain<'a>(
|
||||
evt: &'a GraphEvent,
|
||||
graph: &EnteGraph,
|
||||
) -> Option<(BrainEventKind, SubjectInfo)> {
|
||||
match evt {
|
||||
GraphEvent::EnteDied { id, .. } => {
|
||||
Some((BrainEventKind::EnteDied, subject_info_for(graph, *id)))
|
||||
}
|
||||
GraphEvent::SpawnRequest { card, .. } => {
|
||||
// El "sujeto" del spawn es el child que va a nacer.
|
||||
let info = SubjectInfo {
|
||||
id: Some(card.id),
|
||||
label: Some(card.label.clone()),
|
||||
capabilities: card.provides.iter().cloned().collect(),
|
||||
};
|
||||
Some((BrainEventKind::EnteSpawned, info))
|
||||
}
|
||||
GraphEvent::BusRequest { from, request, .. } => {
|
||||
let kind = match request {
|
||||
ente_bus::BusRequest::Announce { .. } => BrainEventKind::BusAnnounce,
|
||||
ente_bus::BusRequest::Invoke { cap, .. } => {
|
||||
BrainEventKind::BusInvokeOf(cap.clone())
|
||||
}
|
||||
_ => BrainEventKind::BusInvoke,
|
||||
};
|
||||
let info = match from {
|
||||
Some(id) => subject_info_for(graph, *id),
|
||||
None => SubjectInfo::default(),
|
||||
};
|
||||
Some((kind, info))
|
||||
}
|
||||
GraphEvent::CapabilityRequested { from, .. } => {
|
||||
Some((BrainEventKind::BusInvoke, subject_info_for(graph, *from)))
|
||||
}
|
||||
// Responses, ConnClosed, Shutdown — irrelevantes para reglas
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn subject_info_for(graph: &EnteGraph, id: Ulid) -> SubjectInfo {
|
||||
// Acceso de sólo lectura — usamos el método público lookup_pid + cards
|
||||
// virtuales en el grafo. Si el Ente no existe (ya disuelto), info vacía.
|
||||
if let Some(card) = graph.card_for(&id) {
|
||||
SubjectInfo {
|
||||
id: Some(id),
|
||||
label: Some(card.label.clone()),
|
||||
capabilities: card.provides.iter().cloned().collect(),
|
||||
}
|
||||
} else {
|
||||
SubjectInfo { id: Some(id), label: None, capabilities: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// `ActionSink` que enruta acciones del cerebro al bucle primordial.
|
||||
pub struct GraphSink {
|
||||
pub graph_tx: mpsc::Sender<GraphEvent>,
|
||||
pub requester: Ulid,
|
||||
}
|
||||
|
||||
impl ActionSink for GraphSink {
|
||||
fn spawn(&self, card_blob: &str) {
|
||||
// El blob es JSON de EntityCard.
|
||||
match serde_json::from_str::<ente_card::EntityCard>(card_blob) {
|
||||
Ok(card) => {
|
||||
let evt = GraphEvent::SpawnRequest { card, requester: self.requester };
|
||||
if self.graph_tx.try_send(evt).is_err() {
|
||||
warn!("brain spawn: graph_tx lleno o cerrado");
|
||||
}
|
||||
}
|
||||
Err(e) => warn!(?e, "brain spawn: blob no parseable como EntityCard JSON"),
|
||||
}
|
||||
}
|
||||
|
||||
fn invoke(&self, target_cap: Capability, blob: Vec<u8>) {
|
||||
// Sin BusClient en proceso — el sink registra la intención. Una mejora
|
||||
// futura: spawn un BusClient::connect + call. Por ahora log estructurado.
|
||||
warn!(?target_cap, blob_len = blob.len(), "brain invoke: no bus client en glue (TODO)");
|
||||
}
|
||||
|
||||
fn notify(&self, target_id: Ulid, message: &str) {
|
||||
warn!(%target_id, %message, "brain notify: no implementado en glue");
|
||||
}
|
||||
|
||||
fn inhibit(&self, reason: &str) {
|
||||
warn!(%reason, "brain inhibit: no implementado en glue");
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper para que el grafo exponga la Card de un Ente vivo. Lo añadimos como
|
||||
/// trait extension porque graph::EnteGraph mantiene `incarnated` privado.
|
||||
pub trait GraphCardLookup {
|
||||
fn card_for(&self, id: &Ulid) -> Option<&ente_card::EntityCard>;
|
||||
}
|
||||
|
||||
impl GraphCardLookup for EnteGraph {
|
||||
fn card_for(&self, id: &Ulid) -> Option<&ente_card::EntityCard> {
|
||||
// Acceso vía método público que añadiremos en graph/mod.rs.
|
||||
self.peek_card(id)
|
||||
}
|
||||
}
|
||||
|
||||
// Eliminar el campo `_unused` que rustc puede quejarse — placeholder para
|
||||
// evitar warning si algún field queda sin uso.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize)]
|
||||
struct _Touch {}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Listener del bus interno. Vive en PID 1, acepta conexiones de Entes hijos,
|
||||
//! extrae credenciales del kernel vía SO_PEERCRED, y enruta cada request al
|
||||
//! grafo. Conexión bidireccional: el grafo puede *empujar* requests hacia
|
||||
//! una conexión registrada (forwarding de Invoke al proveedor).
|
||||
//!
|
||||
//! ## Por qué bidireccional
|
||||
//!
|
||||
//! Un Ente que provee `Capability::Endpoint` debe poder *recibir* invokes
|
||||
//! sin abrir más sockets. Después de Announce, el grafo guarda el lado de
|
||||
//! escritura de su conexión y lo usa para forwardear.
|
||||
|
||||
use crate::events::GraphEvent;
|
||||
use ente_bus::{read_frame, write_frame, BusMessage, BusPayload, BusResponse, PeerCreds};
|
||||
use nix::sys::socket::{getsockopt, sockopt::PeerCredentials};
|
||||
use std::path::PathBuf;
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{error, info, trace, warn};
|
||||
use ulid::Ulid;
|
||||
|
||||
pub fn default_socket_path() -> PathBuf {
|
||||
if let Ok(p) = std::env::var(ente_bus::ENV_BUS_SOCK) {
|
||||
return p.into();
|
||||
}
|
||||
let runtime = std::env::var("XDG_RUNTIME_DIR")
|
||||
.unwrap_or_else(|_| std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()));
|
||||
let user = std::env::var("USER").unwrap_or_else(|_| "ente".into());
|
||||
format!("{runtime}/ente-bus-{user}.sock").into()
|
||||
}
|
||||
|
||||
pub fn spawn_bus(path: PathBuf, graph_tx: mpsc::Sender<GraphEvent>) -> anyhow::Result<PathBuf> {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let listener = UnixListener::bind(&path)?;
|
||||
info!(path = %path.display(), "bus interno escuchando");
|
||||
|
||||
let path_returned = path.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, _addr)) => {
|
||||
let tx = graph_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle_conn(stream, tx).await {
|
||||
warn!(?e, "bus connection ended");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
error!(?e, "bus accept failed, listener cerrando");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(path_returned)
|
||||
}
|
||||
|
||||
async fn handle_conn(stream: UnixStream, graph_tx: mpsc::Sender<GraphEvent>) -> anyhow::Result<()> {
|
||||
// SO_PEERCRED: el kernel adjunta pid/uid/gid al socket en connect/accept.
|
||||
// No-falsificable desde el cliente.
|
||||
let creds = getsockopt(&stream, PeerCredentials)
|
||||
.map_err(|e| anyhow::anyhow!("getsockopt PEERCRED: {e}"))?;
|
||||
let peer = PeerCreds {
|
||||
pid: creds.pid(),
|
||||
uid: creds.uid(),
|
||||
gid: creds.gid(),
|
||||
};
|
||||
trace!(?peer, "bus conn aceptada");
|
||||
|
||||
let (mut reader, mut writer) = stream.into_split();
|
||||
let (out_tx, mut out_rx) = mpsc::channel::<BusMessage>(64);
|
||||
|
||||
// Writer task: única vía de escritura al socket. Multiplexa entre
|
||||
// respuestas a peticiones del cliente y forwards iniciados por el grafo.
|
||||
let writer_task = tokio::spawn(async move {
|
||||
while let Some(msg) = out_rx.recv().await {
|
||||
if let Err(e) = write_frame(&mut writer, &msg).await {
|
||||
warn!(?e, "bus writer falló, terminando");
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut announced_id: Option<Ulid> = None;
|
||||
let result: anyhow::Result<()> = (async {
|
||||
loop {
|
||||
let msg = match read_frame(&mut reader).await {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
trace!(?e, "bus conn read terminó");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
match msg.payload {
|
||||
BusPayload::Request(req) => {
|
||||
let is_announce = matches!(req, ente_bus::BusRequest::Announce { .. });
|
||||
let (reply_tx, reply_rx) = oneshot::channel();
|
||||
if graph_tx.send(GraphEvent::BusRequest {
|
||||
peer,
|
||||
from: msg.from,
|
||||
request: req,
|
||||
outbound: out_tx.clone(),
|
||||
reply: reply_tx,
|
||||
}).await.is_err() {
|
||||
warn!("graph cerrado, terminando bus connection");
|
||||
return Ok(());
|
||||
}
|
||||
let response = reply_rx.await.unwrap_or_else(|_| {
|
||||
BusResponse::Error("graph dropped reply channel".into())
|
||||
});
|
||||
if is_announce && matches!(response, BusResponse::Ok) {
|
||||
// Auth del Announce ya fue verificada por el grafo;
|
||||
// memorizamos para cleanup en cierre.
|
||||
announced_id = msg.from;
|
||||
}
|
||||
let out = BusMessage {
|
||||
from: None,
|
||||
seq: msg.seq,
|
||||
payload: BusPayload::Response(response),
|
||||
};
|
||||
if out_tx.send(out).await.is_err() { return Ok(()); }
|
||||
}
|
||||
BusPayload::Response(resp) => {
|
||||
// Respuesta a un Invoke que el grafo forwardeó a este peer.
|
||||
let _ = graph_tx.send(GraphEvent::BusResponse {
|
||||
seq: msg.seq,
|
||||
response: resp,
|
||||
}).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
|
||||
if let Some(id) = announced_id {
|
||||
let _ = graph_tx.send(GraphEvent::BusConnClosed { ente_id: Some(id) }).await;
|
||||
}
|
||||
writer_task.abort();
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Eventos internos del bucle primordial. Todo cambio de estado del fractal
|
||||
//! pasa por aquí — la única vía de mutación del grafo desde tasks externas.
|
||||
|
||||
use ente_bus::{BusMessage, BusRequest, BusResponse, PeerCreds};
|
||||
use ente_card::{Capability, EntityCard};
|
||||
use nix::sys::signal::Signal;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use ulid::Ulid;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum GraphEvent {
|
||||
EnteDied { id: Ulid, status: ExitStatus },
|
||||
CapabilityRequested {
|
||||
from: Ulid,
|
||||
cap: Capability,
|
||||
reply: oneshot::Sender<CapabilityGrant>,
|
||||
},
|
||||
SpawnRequest { card: EntityCard, requester: Ulid },
|
||||
/// Request del bus interno. `peer` es no-falsificable (kernel-injected
|
||||
/// via SO_PEERCRED). `from` es la identidad reclamada por el cliente —
|
||||
/// el grafo la verifica contra `peer.pid`.
|
||||
BusRequest {
|
||||
peer: PeerCreds,
|
||||
from: Option<Ulid>,
|
||||
request: BusRequest,
|
||||
outbound: mpsc::Sender<BusMessage>,
|
||||
reply: oneshot::Sender<BusResponse>,
|
||||
},
|
||||
/// Response a un Invoke forwardeado por el grafo a un proveedor.
|
||||
/// `seq` debe coincidir con una entry en pending_invokes.
|
||||
BusResponse { seq: u64, response: BusResponse },
|
||||
/// Cliente del bus cerró su conexión. Si había anunciado identidad,
|
||||
/// el grafo retira esa conexión del registry.
|
||||
BusConnClosed { ente_id: Option<Ulid> },
|
||||
Shutdown { reason: ShutdownReason },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ExitStatus {
|
||||
Exit(i32),
|
||||
Killed(Signal),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ShutdownReason {
|
||||
SeedRequested,
|
||||
Signal(Signal),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CapabilityGrant {
|
||||
Granted { token: u64 },
|
||||
NoProvider,
|
||||
Denied { reason: &'static str },
|
||||
/// El holder ya tiene el máximo de tokens activos para esta cap.
|
||||
/// Debe esperar a que alguno expire o renovar uno existente.
|
||||
QuotaExceeded { active: u32, limit: u32 },
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Bus mediator: integración de `EnteGraph` con el bus interno.
|
||||
//!
|
||||
//! Responsabilidades:
|
||||
//! - Auth de Announce (verificar identidad reclamada contra SO_PEERCRED)
|
||||
//! - Registro de conexiones (`bus_connections` indexado por Ulid)
|
||||
//! - Forwarding de Invokes a proveedores
|
||||
//! - Tracking de invokes en vuelo (`pending_invokes` por seq)
|
||||
//! - Cleanup en cierre de conexión
|
||||
|
||||
use super::{EnteGraph, SERVER_SEQ_FLAG};
|
||||
use ente_bus::{BusMessage, BusPayload, BusRequest, BusResponse, EnteInfo, PeerCreds};
|
||||
use ente_card::Capability;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{debug, info, warn};
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Operaciones que requieren identidad verificada en el bus.
|
||||
///
|
||||
/// - `Announce`: establece bus_connections para forwarding.
|
||||
/// - `UpdateCapabilities`: muta dynamic_provides del Ente — sólo el dueño.
|
||||
///
|
||||
/// Invoke, ListEntes y power-mgmt se aceptan anonymous — políticas por
|
||||
/// capacidad se aplican aguas abajo, no aquí.
|
||||
fn requires_auth(req: &BusRequest) -> bool {
|
||||
matches!(
|
||||
req,
|
||||
BusRequest::Announce { .. } | BusRequest::UpdateCapabilities { .. }
|
||||
)
|
||||
}
|
||||
|
||||
impl EnteGraph {
|
||||
pub async fn on_bus_request(
|
||||
&mut self,
|
||||
peer: PeerCreds,
|
||||
from: Option<Ulid>,
|
||||
request: BusRequest,
|
||||
outbound: mpsc::Sender<BusMessage>,
|
||||
reply: oneshot::Sender<BusResponse>,
|
||||
) {
|
||||
// ---- Auth: kernel-injected SO_PEERCRED vs identidad reclamada ----
|
||||
let from_authenticated = match from {
|
||||
None => None,
|
||||
Some(claimed) => {
|
||||
let expected = self.incarnated.get(&claimed).and_then(|i| i.pid);
|
||||
match expected {
|
||||
Some(p) if p.as_raw() == peer.pid => Some(claimed),
|
||||
Some(p) => {
|
||||
warn!(
|
||||
claimed = %claimed, expected_pid = p.as_raw(),
|
||||
actual_pid = peer.pid,
|
||||
"identity mismatch — rechazando request"
|
||||
);
|
||||
let _ = reply.send(BusResponse::Error("identity mismatch".into()));
|
||||
return;
|
||||
}
|
||||
None => {
|
||||
warn!(?claimed, peer_pid = peer.pid, "Ente desconocido reclamando identidad");
|
||||
let _ = reply.send(BusResponse::Error("unknown ente claimed".into()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if requires_auth(&request) && from_authenticated.is_none() {
|
||||
let _ = reply.send(BusResponse::Error("auth required for this request".into()));
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- Dispatch ----
|
||||
match request {
|
||||
BusRequest::Announce { capabilities } => {
|
||||
let id = from_authenticated.expect("auth-required guarantees Some");
|
||||
let label = self.incarnated.get(&id).map(|i| i.card.label.clone())
|
||||
.unwrap_or_else(|| "anónimo".into());
|
||||
info!(%id, %label, ?capabilities, peer_pid = peer.pid, "Announce autenticado");
|
||||
self.bus_connections.insert(id, outbound);
|
||||
let _ = reply.send(BusResponse::Ok);
|
||||
}
|
||||
BusRequest::ListEntes => {
|
||||
let entes = self.incarnated.values()
|
||||
.map(|i| EnteInfo {
|
||||
id: i.card.id,
|
||||
label: i.card.label.clone(),
|
||||
provides: i.card.provides.iter().cloned().collect(),
|
||||
pid: i.pid.map(|p| p.as_raw()),
|
||||
})
|
||||
.collect();
|
||||
let _ = reply.send(BusResponse::Entes(entes));
|
||||
}
|
||||
BusRequest::PowerOff { interactive } => {
|
||||
info!(?from_authenticated, interactive, peer_pid = peer.pid, "PowerOff via bus");
|
||||
let _ = reply.send(BusResponse::Ok);
|
||||
}
|
||||
BusRequest::Reboot { interactive } => {
|
||||
info!(?from_authenticated, interactive, "Reboot via bus");
|
||||
let _ = reply.send(BusResponse::Ok);
|
||||
}
|
||||
BusRequest::Suspend { interactive } => {
|
||||
info!(?from_authenticated, interactive, "Suspend via bus");
|
||||
let _ = reply.send(BusResponse::Ok);
|
||||
}
|
||||
BusRequest::Hibernate { interactive } => {
|
||||
info!(?from_authenticated, interactive, "Hibernate via bus");
|
||||
let _ = reply.send(BusResponse::Ok);
|
||||
}
|
||||
BusRequest::Invoke { cap, blob } => {
|
||||
self.forward_invoke(from_authenticated, cap, blob, reply).await;
|
||||
}
|
||||
BusRequest::UpdateCapabilities { adds, removes } => {
|
||||
let id = from_authenticated.expect("auth-required guarantees Some");
|
||||
self.apply_capability_update(id, adds, removes);
|
||||
let _ = reply.send(BusResponse::Ok);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Muta `dynamic_provides` del Ente y actualiza el índice global de
|
||||
/// providers. La Card original (immutable) no se toca.
|
||||
fn apply_capability_update(
|
||||
&mut self,
|
||||
ente_id: Ulid,
|
||||
adds: Vec<Capability>,
|
||||
removes: Vec<Capability>,
|
||||
) {
|
||||
// Adiciones: dedupe contra Card.provides + dynamic_provides existentes.
|
||||
let mut added = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
if let Some(inc) = self.incarnated.get_mut(&ente_id) {
|
||||
for cap in adds {
|
||||
if inc.card.provides.contains(&cap) || inc.dynamic_provides.contains(&cap) {
|
||||
continue; // ya provista, no-op
|
||||
}
|
||||
inc.dynamic_provides.insert(cap.clone());
|
||||
added.push(cap);
|
||||
}
|
||||
for cap in removes {
|
||||
if inc.dynamic_provides.remove(&cap) {
|
||||
removed.push(cap);
|
||||
}
|
||||
// Caps de la Card original no se pueden quitar — silenciosamente
|
||||
// ignoradas. Una Card es contrato; sólo el dynamic es mutable.
|
||||
}
|
||||
}
|
||||
// Actualizar índice global. Hacemos esto fuera del scope `inc` para
|
||||
// evitar el doble-borrow de self.
|
||||
for cap in &added {
|
||||
self.register_dynamic_cap(ente_id, cap.clone());
|
||||
}
|
||||
for cap in &removed {
|
||||
self.unregister_dynamic_cap(ente_id, cap);
|
||||
// Revocar grants emitidos contra esta cap por este Ente.
|
||||
let revoked: Vec<u64> = self.grants.iter()
|
||||
.filter(|(_, g)| g.provider == ente_id && &g.cap == cap)
|
||||
.map(|(t, _)| *t)
|
||||
.collect();
|
||||
for t in revoked {
|
||||
self.grants.remove(&t);
|
||||
}
|
||||
}
|
||||
info!(
|
||||
%ente_id,
|
||||
added_count = added.len(),
|
||||
removed_count = removed.len(),
|
||||
"capabilities actualizadas en runtime"
|
||||
);
|
||||
}
|
||||
|
||||
/// Enruta un Invoke al proveedor real de la capacidad. Aloca un seq
|
||||
/// server-side, registra el reply oneshot en `pending_invokes`, y empuja
|
||||
/// el request por la conexión del proveedor.
|
||||
async fn forward_invoke(
|
||||
&mut self,
|
||||
from: Option<Ulid>,
|
||||
cap: Capability,
|
||||
blob: Vec<u8>,
|
||||
reply: oneshot::Sender<BusResponse>,
|
||||
) {
|
||||
let provider_id = match self.pick_invokable_provider(&cap) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let _ = reply.send(BusResponse::Error(format!("sin proveedor invokable para {cap:?}")));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let outbound = match self.bus_connections.get(&provider_id) {
|
||||
Some(o) => o.clone(),
|
||||
None => {
|
||||
let _ = reply.send(BusResponse::Error("proveedor no conectado al bus".into()));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let seq = self.alloc_invoke_seq();
|
||||
self.pending_invokes.insert(seq, reply);
|
||||
debug!(?from, ?cap, ?provider_id, seq, blob_len = blob.len(), "forwardeando Invoke");
|
||||
|
||||
let msg = BusMessage {
|
||||
from: None,
|
||||
seq,
|
||||
payload: BusPayload::Request(BusRequest::Invoke { cap, blob }),
|
||||
};
|
||||
if outbound.send(msg).await.is_err() {
|
||||
if let Some(orig) = self.pending_invokes.remove(&seq) {
|
||||
let _ = orig.send(BusResponse::Error("conn del proveedor cerrada".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_invokable_provider(&self, cap: &Capability) -> Option<Ulid> {
|
||||
// Sólo proveedores con conexión al bus pueden recibir forwards.
|
||||
// El propio Ente #0 está en `providers` para varias caps pero no
|
||||
// debe recibir forwards — se filtra implícitamente porque la Semilla
|
||||
// no tiene conexión al bus.
|
||||
self.providers.get(cap)?
|
||||
.iter()
|
||||
.find(|id| self.bus_connections.contains_key(id))
|
||||
.copied()
|
||||
}
|
||||
|
||||
pub(in crate::graph) fn alloc_invoke_seq(&mut self) -> u64 {
|
||||
self.next_invoke_seq = self.next_invoke_seq.wrapping_add(1);
|
||||
SERVER_SEQ_FLAG | self.next_invoke_seq
|
||||
}
|
||||
|
||||
pub async fn on_bus_response(&mut self, seq: u64, response: BusResponse) {
|
||||
if let Some(orig) = self.pending_invokes.remove(&seq) {
|
||||
let _ = orig.send(response);
|
||||
} else {
|
||||
warn!(seq, "Response sin pending invoke");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn on_bus_conn_closed(&mut self, ente_id: Option<Ulid>) {
|
||||
if let Some(id) = ente_id {
|
||||
self.bus_connections.remove(&id);
|
||||
// No revocamos providers — la capacidad sigue declarada en su
|
||||
// Card. Sólo perdimos el canal de invocación.
|
||||
debug!(%id, "bus connection cerrada");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Mediación de capabilities: emisión, renovación, revocación de tokens.
|
||||
//!
|
||||
//! Los grants tienen TTL (`DEFAULT_GRANT_TTL`). El cliente debe renovarlos
|
||||
//! periódicamente con `renew_grant(token)`; en caso contrario, el background
|
||||
//! task `purge_expired_grants` los revoca al vencimiento.
|
||||
|
||||
use super::{quota_for_capability, ttl_for_capability, EnteGraph, GrantedCapability};
|
||||
use crate::events::CapabilityGrant;
|
||||
use ente_card::Capability;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::debug;
|
||||
use ulid::Ulid;
|
||||
|
||||
impl EnteGraph {
|
||||
pub async fn mediate_capability(
|
||||
&mut self,
|
||||
from: Ulid,
|
||||
cap: Capability,
|
||||
reply: oneshot::Sender<CapabilityGrant>,
|
||||
) {
|
||||
let grant = match self.providers.get(&cap).and_then(|s| s.iter().next().copied()) {
|
||||
None => CapabilityGrant::NoProvider,
|
||||
Some(provider) => {
|
||||
// Quota: contar tokens vivos para (from, cap). Si excede,
|
||||
// rechazar antes de emitir uno nuevo.
|
||||
let limit = quota_for_capability(&cap);
|
||||
let active = self.active_tokens_for(from, &cap);
|
||||
if active >= limit {
|
||||
CapabilityGrant::QuotaExceeded { active, limit }
|
||||
} else {
|
||||
let token = self.next_token;
|
||||
self.next_token += 1;
|
||||
let ttl = ttl_for_capability(&cap);
|
||||
let expires_at = Instant::now() + ttl;
|
||||
self.grants.insert(token, GrantedCapability {
|
||||
cap: cap.clone(),
|
||||
provider,
|
||||
holder: from,
|
||||
expires_at,
|
||||
});
|
||||
CapabilityGrant::Granted { token }
|
||||
}
|
||||
}
|
||||
};
|
||||
let _ = reply.send(grant);
|
||||
}
|
||||
|
||||
/// Cuenta tokens vivos (no expirados) emitidos a un holder para una cap.
|
||||
pub fn active_tokens_for(&self, holder: Ulid, cap: &Capability) -> u32 {
|
||||
let now = Instant::now();
|
||||
self.grants.values()
|
||||
.filter(|g| g.holder == holder && &g.cap == cap && g.expires_at > now)
|
||||
.count() as u32
|
||||
}
|
||||
|
||||
/// Extiende un grant existente. Devuelve `true` si renovó. Si el token
|
||||
/// no existe o ya expiró, `false` (el cliente debe re-acquire).
|
||||
/// Usa el TTL específico de la cap del grant.
|
||||
pub fn renew_grant(&mut self, token: u64) -> bool {
|
||||
let now = Instant::now();
|
||||
if let Some(g) = self.grants.get_mut(&token) {
|
||||
if g.expires_at > now {
|
||||
g.expires_at = now + ttl_for_capability(&g.cap);
|
||||
return true;
|
||||
}
|
||||
// Expired — purgamos aquí mismo.
|
||||
self.grants.remove(&token);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// GC: elimina grants vencidos. Devuelve cuántos fueron purgados.
|
||||
pub fn purge_expired_grants(&mut self) -> usize {
|
||||
let now = Instant::now();
|
||||
let expired: Vec<u64> = self.grants.iter()
|
||||
.filter(|(_, g)| g.expires_at <= now)
|
||||
.map(|(t, _)| *t)
|
||||
.collect();
|
||||
for t in &expired {
|
||||
self.grants.remove(t);
|
||||
}
|
||||
if !expired.is_empty() {
|
||||
debug!(count = expired.len(), "grants expirados purgados");
|
||||
}
|
||||
expired.len()
|
||||
}
|
||||
|
||||
/// Cuenta de grants vivos (no expirados). Usado por métricas.
|
||||
pub fn active_grants_count(&self) -> usize {
|
||||
let now = Instant::now();
|
||||
self.grants.values().filter(|g| g.expires_at > now).count()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Device registry: mantiene el índice de dispositivos del kernel presentes,
|
||||
//! traduce uevents en cambios de `Capability::Device { class }`.
|
||||
|
||||
use super::EnteGraph;
|
||||
use crate::events::GraphEvent;
|
||||
use ente_card::{Capability, DeviceClass};
|
||||
use ente_kernel::{UAction, UEvent};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
impl EnteGraph {
|
||||
pub async fn on_uevent(&mut self, evt: UEvent, _tx: &mpsc::Sender<GraphEvent>) {
|
||||
let class = match &evt.device_class {
|
||||
Some(c) => c.clone(),
|
||||
None => return, // subsystems sin DeviceClass mapeada — ignoramos.
|
||||
};
|
||||
match evt.action {
|
||||
UAction::Add | UAction::Bind | UAction::Online => {
|
||||
let was_first = self.devices_of_class(&class) == 0;
|
||||
self.devices.insert(evt.devpath.clone(), evt.clone());
|
||||
if was_first {
|
||||
// Primera instancia de la clase → la registramos como
|
||||
// capacidad disponible. El "proveedor" virtual es el
|
||||
// Ente #0 (kernel surface).
|
||||
let cap = Capability::Device { class: class.clone() };
|
||||
self.providers.entry(cap).or_default().insert(self.seed.id);
|
||||
info!(?class, devpath = %evt.devpath, "device capability disponible");
|
||||
}
|
||||
}
|
||||
UAction::Remove | UAction::Unbind | UAction::Offline => {
|
||||
self.devices.remove(&evt.devpath);
|
||||
if self.devices_of_class(&class) == 0 {
|
||||
let cap = Capability::Device { class: class.clone() };
|
||||
if let Some(set) = self.providers.get_mut(&cap) {
|
||||
set.remove(&self.seed.id);
|
||||
}
|
||||
let revoked: Vec<u64> = self.grants.iter()
|
||||
.filter(|(_, g)| g.cap == cap)
|
||||
.map(|(t, _)| *t)
|
||||
.collect();
|
||||
for t in revoked {
|
||||
self.grants.remove(&t);
|
||||
}
|
||||
warn!(?class, "última instancia removida — capacidad revocada");
|
||||
}
|
||||
}
|
||||
UAction::Change | UAction::Move => {
|
||||
self.devices.insert(evt.devpath.clone(), evt);
|
||||
debug!(?class, "device modified");
|
||||
}
|
||||
UAction::Unknown => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn devices_of_class(&self, class: &DeviceClass) -> usize {
|
||||
self.devices.values()
|
||||
.filter(|e| e.device_class.as_ref() == Some(class))
|
||||
.count()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Encarnación, muerte y supervisión.
|
||||
//!
|
||||
//! Aquí vive el flujo: Card → autorizar → soma::incarnate / wasm → registro
|
||||
//! en el grafo → SIGCHLD → on_death → Restart/OneShot/Delegate.
|
||||
|
||||
use super::{EnteGraph, Incarnated};
|
||||
use crate::events::{ExitStatus, GraphEvent};
|
||||
use ente_bus::{BusMessage, BusPayload, BusRequest};
|
||||
use ente_card::{Capability, EntityCard, Payload, Supervision};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{info, warn};
|
||||
use ulid::Ulid;
|
||||
|
||||
impl EnteGraph {
|
||||
/// Encarna las dependencias declaradas en la Semilla. Único punto donde
|
||||
/// el Init "decide": después sólo reacciona.
|
||||
pub async fn instantiate_seed_dependencies(
|
||||
&mut self,
|
||||
_tx: &mpsc::Sender<GraphEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let cards = std::mem::take(&mut self.pending_genesis);
|
||||
if cards.is_empty() {
|
||||
info!(seed = %self.seed.label, "semilla sin genesis cards");
|
||||
return Ok(());
|
||||
}
|
||||
info!(seed = %self.seed.label, count = cards.len(), "instanciando genesis");
|
||||
let seed_id = self.seed.id;
|
||||
for card in cards {
|
||||
if let Err(e) = self.authorize_and_spawn(card, seed_id).await {
|
||||
warn!(?e, "genesis card falló");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Spawn solicitado por un Ente con `Capability::Spawn`. Verifica auth,
|
||||
/// requires del grafo, y delega la encarnación al backend correspondiente
|
||||
/// (`ente_soma` para procesos, `ente_wasm` para Wasm).
|
||||
pub async fn authorize_and_spawn(
|
||||
&mut self,
|
||||
mut card: EntityCard,
|
||||
requester: Ulid,
|
||||
) -> anyhow::Result<()> {
|
||||
if !self.holder_has(requester, &Capability::Spawn) {
|
||||
warn!(?requester, "spawn denied: lacks Capability::Spawn");
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(e) = card.validate() {
|
||||
warn!(?e, label = %card.label, "card inválida, spawn rechazado");
|
||||
return Ok(());
|
||||
}
|
||||
// Falla rápida sobre `requires` — mejor que daemons en bucle.
|
||||
for req in &card.requires {
|
||||
if !self.providers.contains_key(req) {
|
||||
warn!(?req, label = %card.label, "requires no satisfecho");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Lineage por defecto = quien pidió el spawn.
|
||||
if card.lineage.is_none() {
|
||||
card.lineage = Some(requester);
|
||||
}
|
||||
|
||||
let pid = match &card.payload {
|
||||
Payload::Virtual => None,
|
||||
Payload::Native { .. } | Payload::Legacy { .. } => {
|
||||
Some(ente_soma::incarnate(&card)?)
|
||||
}
|
||||
Payload::Wasm { module_sha256, entry } => {
|
||||
// Wasm: hilo dedicado, sin PID. Su muerte se observa por
|
||||
// estado del runtime, no por SIGCHLD.
|
||||
let bytes = ente_cas::resolve(module_sha256)
|
||||
.map_err(|e| anyhow::anyhow!("CAS resolve para {}: {e}", card.label))?;
|
||||
ente_wasm::incarnate_wasm(&card, bytes, entry.clone())?;
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(p) = pid {
|
||||
self.by_pid.insert(p.as_raw(), card.id);
|
||||
}
|
||||
self.register_provider(&card);
|
||||
if let Some(parent) = card.lineage {
|
||||
self.children.entry(parent).or_default().push(card.id);
|
||||
}
|
||||
info!(label = %card.label, ?pid, lineage = ?card.lineage, "Ente encarnado");
|
||||
self.incarnated.insert(card.id, Incarnated {
|
||||
card, pid,
|
||||
dynamic_provides: std::collections::BTreeSet::new(),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn on_death(
|
||||
&mut self,
|
||||
id: Ulid,
|
||||
status: ExitStatus,
|
||||
_tx: &mpsc::Sender<GraphEvent>,
|
||||
) {
|
||||
let Some(inc) = self.incarnated.remove(&id) else { return };
|
||||
if let Some(p) = inc.pid {
|
||||
self.by_pid.remove(&p.as_raw());
|
||||
}
|
||||
self.unregister_provider(&inc.card);
|
||||
if let Some(parent) = inc.card.lineage {
|
||||
if let Some(siblings) = self.children.get_mut(&parent) {
|
||||
siblings.retain(|c| c != &id);
|
||||
}
|
||||
}
|
||||
info!(label = %inc.card.label, ?status, "Ente disuelto");
|
||||
|
||||
match inc.card.supervision.clone() {
|
||||
Supervision::Restart { initial, max: _ } => {
|
||||
// Backoff exponencial: TODO real con timer del runtime.
|
||||
tokio::time::sleep(initial).await;
|
||||
let new_card = EntityCard { id: Ulid::new(), ..inc.card };
|
||||
if let Err(e) = self.authorize_and_spawn(new_card, self.seed.id).await {
|
||||
warn!(?e, "restart falló");
|
||||
}
|
||||
}
|
||||
Supervision::OneShot => {}
|
||||
Supervision::Delegate => {
|
||||
self.notify_lineage_of_death(&inc, &status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fire-and-forget: si el parent tiene conexión al bus, le forwardeamos
|
||||
/// un Invoke con la muerte del hijo. Sin retry, sin backpressure.
|
||||
fn notify_lineage_of_death(&mut self, inc: &Incarnated, status: &ExitStatus) {
|
||||
let Some(parent) = inc.card.lineage else { return };
|
||||
info!(
|
||||
child = %inc.card.id, parent = %parent, label = %inc.card.label,
|
||||
?status,
|
||||
"Supervision::Delegate — muerte notificada al lineage"
|
||||
);
|
||||
if let Some(out) = self.bus_connections.get(&parent).cloned() {
|
||||
let blob = format!("{}:{:?}", inc.card.id, status);
|
||||
let seq = self.alloc_invoke_seq();
|
||||
let msg = BusMessage {
|
||||
from: None,
|
||||
seq,
|
||||
payload: BusPayload::Request(BusRequest::Invoke {
|
||||
cap: Capability::Endpoint {
|
||||
interface: ente_card::InterfaceId([0xde; 16]),
|
||||
version: 1,
|
||||
},
|
||||
blob: blob.into_bytes(),
|
||||
}),
|
||||
};
|
||||
let _ = out.try_send(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! `EnteGraph`: estado del fractal vivo en PID 1.
|
||||
//!
|
||||
//! Diseño:
|
||||
//! - Submódulos por concern: lifecycle, topology, shutdown, bus_mediator,
|
||||
//! devices, capabilities. Cada uno extiende `impl EnteGraph` con métodos
|
||||
//! relacionados.
|
||||
//! - Estado plano (no substructs todavía) — la separación es por
|
||||
//! comportamiento, no por compartimentación de datos.
|
||||
//! - Toda mutación pasa por el bucle primordial vía `GraphEvent`. Los
|
||||
//! submódulos se llaman desde `main.rs::primordial_loop`.
|
||||
|
||||
mod bus_mediator;
|
||||
mod capabilities;
|
||||
mod devices;
|
||||
mod lifecycle;
|
||||
mod shutdown;
|
||||
mod topology;
|
||||
|
||||
use ente_bus::{BusMessage, BusResponse};
|
||||
use ente_card::{Capability, EntityCard};
|
||||
use nix::unistd::Pid;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use ulid::Ulid;
|
||||
|
||||
pub use shutdown::SHUTDOWN_GRACE;
|
||||
|
||||
/// Bit alto encendido en `seq` para invokes server-iniciados — evita choque
|
||||
/// con secuencias allocadas por clientes.
|
||||
pub(in crate::graph) const SERVER_SEQ_FLAG: u64 = 1u64 << 63;
|
||||
|
||||
pub struct EnteGraph {
|
||||
pub(in crate::graph) seed: EntityCard,
|
||||
/// Entes encarnados como proceso o nodo virtual. id↔pid bidireccional.
|
||||
pub(in crate::graph) incarnated: HashMap<Ulid, Incarnated>,
|
||||
pub(in crate::graph) by_pid: HashMap<i32, Ulid>,
|
||||
/// Quién provee qué capacidad. Resuelve `requires` y `pick_invokable`.
|
||||
pub(in crate::graph) providers: BTreeMap<Capability, BTreeSet<Ulid>>,
|
||||
/// Tokens de capability emitidos. Revocables al morir el proveedor.
|
||||
pub(in crate::graph) next_token: u64,
|
||||
pub(in crate::graph) grants: HashMap<u64, GrantedCapability>,
|
||||
/// Dispositivos del kernel presentes (devpath → última UEvent).
|
||||
pub(in crate::graph) devices: HashMap<String, ente_kernel::UEvent>,
|
||||
/// Cards genesis pendientes de instanciar (extraídas de la Semilla).
|
||||
pub(in crate::graph) pending_genesis: Vec<EntityCard>,
|
||||
/// Hijos directos por lineage. parent → [child, ...].
|
||||
pub(in crate::graph) children: HashMap<Ulid, Vec<Ulid>>,
|
||||
/// Conexiones del bus indexadas por la identidad anunciada y verificada
|
||||
/// con SO_PEERCRED. El value es el extremo de escritura del writer task.
|
||||
pub(in crate::graph) bus_connections: HashMap<Ulid, mpsc::Sender<BusMessage>>,
|
||||
/// Invokes forwardeados pendientes de respuesta del proveedor.
|
||||
pub(in crate::graph) pending_invokes: HashMap<u64, oneshot::Sender<BusResponse>>,
|
||||
pub(in crate::graph) next_invoke_seq: u64,
|
||||
}
|
||||
|
||||
pub(in crate::graph) struct Incarnated {
|
||||
pub card: EntityCard,
|
||||
pub pid: Option<Pid>,
|
||||
/// Capacidades añadidas en runtime vía BusRequest::UpdateCapabilities.
|
||||
/// La Card original es immutable; la "vista efectiva" del Ente es
|
||||
/// `card.provides ∪ dynamic_provides`.
|
||||
pub dynamic_provides: BTreeSet<Capability>,
|
||||
}
|
||||
|
||||
pub(in crate::graph) struct GrantedCapability {
|
||||
pub cap: Capability,
|
||||
pub provider: Ulid,
|
||||
pub holder: Ulid,
|
||||
/// Instante en el que el grant deja de ser válido. El garbage collector
|
||||
/// del cerebro purga grants con `Instant::now() > expires_at`.
|
||||
pub expires_at: std::time::Instant,
|
||||
}
|
||||
|
||||
/// TTL default para grants cuando la cap no tiene override. 60s es un
|
||||
/// compromiso: largo enough para evitar churn en patrones interactivos,
|
||||
/// corto enough para que credenciales filtradas expiren rápidamente.
|
||||
pub const DEFAULT_GRANT_TTL: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// Quota máxima de tokens activos por (holder, cap). Caps escaladas tienen
|
||||
/// quota baja para limitar fugas de credenciales; caps de uso frecuente
|
||||
/// (Endpoint, Journal) son más laxas.
|
||||
pub fn quota_for_capability(cap: &Capability) -> u32 {
|
||||
match cap {
|
||||
// Caps escaladas: pocos tokens, fuerza patrón request-act-release.
|
||||
Capability::Spawn => 2,
|
||||
Capability::FilesystemRoot => 2,
|
||||
Capability::Device { .. } => 4,
|
||||
// Caps de propósito general.
|
||||
Capability::Endpoint { .. } => 16,
|
||||
Capability::KernelNetlink(_) => 4,
|
||||
Capability::LegacyLogind => 8,
|
||||
// Logging: hasta 32 streams.
|
||||
Capability::Journal => 32,
|
||||
}
|
||||
}
|
||||
|
||||
/// TTL específico por variante de Capability. Caps de mayor riesgo / costo
|
||||
/// (Spawn, FilesystemRoot) tienen TTL más corto; caps "logging" como
|
||||
/// Journal pueden vivir más.
|
||||
///
|
||||
/// Cualquier cap no listada cae al `DEFAULT_GRANT_TTL`.
|
||||
pub fn ttl_for_capability(cap: &Capability) -> std::time::Duration {
|
||||
use std::time::Duration;
|
||||
match cap {
|
||||
// Caps escaladas: TTL corto para forzar renovación frecuente.
|
||||
Capability::Spawn => Duration::from_secs(30),
|
||||
Capability::FilesystemRoot => Duration::from_secs(30),
|
||||
Capability::Device { .. } => Duration::from_secs(60),
|
||||
// Caps de propósito general.
|
||||
Capability::Endpoint { .. } => Duration::from_secs(300), // 5 min
|
||||
Capability::KernelNetlink(_) => Duration::from_secs(300),
|
||||
Capability::LegacyLogind => Duration::from_secs(300),
|
||||
// Logging puede vivir mucho.
|
||||
Capability::Journal => Duration::from_secs(3600), // 1h
|
||||
}
|
||||
}
|
||||
|
||||
impl EnteGraph {
|
||||
pub fn new(mut seed: EntityCard) -> Self {
|
||||
// Extraemos genesis antes de almacenar la Semilla — evita duplicación
|
||||
// en `incarnated[seed.id]`.
|
||||
let pending_genesis = std::mem::take(&mut seed.genesis);
|
||||
let mut g = Self {
|
||||
seed: seed.clone(),
|
||||
incarnated: HashMap::new(),
|
||||
by_pid: HashMap::new(),
|
||||
providers: BTreeMap::new(),
|
||||
next_token: 1,
|
||||
grants: HashMap::new(),
|
||||
devices: HashMap::new(),
|
||||
pending_genesis,
|
||||
children: HashMap::new(),
|
||||
bus_connections: HashMap::new(),
|
||||
pending_invokes: HashMap::new(),
|
||||
next_invoke_seq: 0,
|
||||
};
|
||||
// El Ente #0 se inscribe a sí mismo como proveedor de las capacidades
|
||||
// que su Card declara — sólo así los hijos pueden requerirlas.
|
||||
g.register_provider(&seed);
|
||||
g.incarnated.insert(seed.id, Incarnated {
|
||||
card: seed, pid: None,
|
||||
dynamic_provides: BTreeSet::new(),
|
||||
});
|
||||
g
|
||||
}
|
||||
|
||||
pub fn lookup_pid(&self, pid: Pid) -> Option<Ulid> {
|
||||
self.by_pid.get(&pid.as_raw()).copied()
|
||||
}
|
||||
|
||||
/// Acceso read-only a la Card de un Ente vivo. Usado por el cerebro
|
||||
/// para hidratar `SubjectInfo` sin clonar todo el mapa.
|
||||
pub fn peek_card(&self, id: &Ulid) -> Option<&EntityCard> {
|
||||
self.incarnated.get(id).map(|i| &i.card)
|
||||
}
|
||||
|
||||
/// Identidad de la Semilla. Usado como `requester` para spawns generados
|
||||
/// por reglas auto-cristalizadas (única identidad con Capability::Spawn).
|
||||
pub fn seed_id(&self) -> Ulid {
|
||||
self.seed.id
|
||||
}
|
||||
|
||||
/// Captura el estado live como snapshot serializable. Excluye la Semilla
|
||||
/// (será re-sintetizada al restore con su seed_id preservado).
|
||||
pub fn snapshot(&self) -> ente_snapshot::FractalSnapshot {
|
||||
let entes: Vec<EntityCard> = self.incarnated.iter()
|
||||
.filter(|(id, _)| **id != self.seed.id)
|
||||
.map(|(_, inc)| inc.card.clone())
|
||||
.collect();
|
||||
ente_snapshot::FractalSnapshot {
|
||||
version: ente_snapshot::SNAPSHOT_VERSION,
|
||||
timestamp_ms: ente_snapshot::now_ms(),
|
||||
seed_id: self.seed.id,
|
||||
seed_label: self.seed.label.clone(),
|
||||
entes,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::graph) fn register_provider(&mut self, card: &EntityCard) {
|
||||
for cap in &card.provides {
|
||||
self.providers.entry(cap.clone()).or_default().insert(card.id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::graph) fn unregister_provider(&mut self, card: &EntityCard) {
|
||||
for cap in &card.provides {
|
||||
if let Some(set) = self.providers.get_mut(cap) {
|
||||
set.remove(&card.id);
|
||||
}
|
||||
}
|
||||
// Revocar grants emitidos por el Ente fallecido.
|
||||
let revoked: Vec<u64> = self.grants.iter()
|
||||
.filter(|(_, g)| g.provider == card.id)
|
||||
.map(|(t, _)| *t)
|
||||
.collect();
|
||||
for t in revoked {
|
||||
self.grants.remove(&t);
|
||||
}
|
||||
}
|
||||
|
||||
/// Quita una capacidad dinámica del índice de providers para un Ente
|
||||
/// específico. Usado al recibir UpdateCapabilities con `removes`.
|
||||
pub(in crate::graph) fn unregister_dynamic_cap(&mut self, ente_id: Ulid, cap: &Capability) {
|
||||
if let Some(set) = self.providers.get_mut(cap) {
|
||||
set.remove(&ente_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserta una capacidad dinámica al índice de providers para un Ente.
|
||||
pub(in crate::graph) fn register_dynamic_cap(&mut self, ente_id: Ulid, cap: Capability) {
|
||||
self.providers.entry(cap).or_default().insert(ente_id);
|
||||
}
|
||||
|
||||
/// El Ente #0 (semilla) tiene todas sus capacidades declaradas. Otros
|
||||
/// las tienen si su Card las declara o si poseen un grant vivo.
|
||||
pub(in crate::graph) fn holder_has(&self, holder: Ulid, cap: &Capability) -> bool {
|
||||
if holder == self.seed.id {
|
||||
return self.seed.provides.contains(cap);
|
||||
}
|
||||
if let Some(inc) = self.incarnated.get(&holder) {
|
||||
if inc.card.provides.contains(cap) { return true; }
|
||||
}
|
||||
self.grants.values().any(|g| g.holder == holder && &g.cap == cap)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Cascade shutdown: SIGTERM en orden topológico (hojas primero), grace
|
||||
//! period, SIGKILL para stragglers, reap final.
|
||||
|
||||
use super::EnteGraph;
|
||||
use nix::errno::Errno;
|
||||
use nix::sys::signal::{kill, Signal};
|
||||
use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
|
||||
use nix::unistd::Pid;
|
||||
use std::time::{Duration, Instant};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// Tiempo que damos a los Entes tras SIGTERM antes de escalar a SIGKILL.
|
||||
pub const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
impl EnteGraph {
|
||||
pub async fn cascade_shutdown(&mut self) {
|
||||
let order = self.topo_order();
|
||||
let pids: Vec<Pid> = order.iter()
|
||||
.filter_map(|id| self.incarnated.get(id).and_then(|i| i.pid))
|
||||
.collect();
|
||||
|
||||
if pids.is_empty() {
|
||||
info!("cascade shutdown: ningún Ente encarnado, salida limpia");
|
||||
return;
|
||||
}
|
||||
|
||||
info!(
|
||||
count = pids.len(), grace_ms = SHUTDOWN_GRACE.as_millis() as u64,
|
||||
"SIGTERM cascade (topológico, hojas primero)"
|
||||
);
|
||||
for pid in &pids {
|
||||
match kill(*pid, Signal::SIGTERM) {
|
||||
Ok(()) => {}
|
||||
Err(Errno::ESRCH) => {} // ya muerto, lo cosecharemos abajo
|
||||
Err(e) => warn!(?pid, ?e, "kill SIGTERM falló"),
|
||||
}
|
||||
}
|
||||
|
||||
let deadline = Instant::now() + SHUTDOWN_GRACE;
|
||||
while Instant::now() < deadline {
|
||||
if !self.incarnated.values().any(|i| i.pid.is_some()) {
|
||||
break;
|
||||
}
|
||||
match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
|
||||
Ok(WaitStatus::Exited(pid, code)) => {
|
||||
self.reap_during_shutdown(pid);
|
||||
debug!(?pid, code, "reaped (exited)");
|
||||
}
|
||||
Ok(WaitStatus::Signaled(pid, sig, _)) => {
|
||||
self.reap_during_shutdown(pid);
|
||||
debug!(?pid, ?sig, "reaped (signaled)");
|
||||
}
|
||||
Ok(WaitStatus::StillAlive) | Err(Errno::EINTR) => {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
Err(Errno::ECHILD) => return,
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
warn!(?e, "waitpid fallo en shutdown grace");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let stragglers: Vec<Pid> = self.incarnated.values()
|
||||
.filter_map(|i| i.pid)
|
||||
.collect();
|
||||
|
||||
if stragglers.is_empty() {
|
||||
info!("cascade shutdown completo (todos los Entes terminaron en gracia)");
|
||||
return;
|
||||
}
|
||||
|
||||
warn!(count = stragglers.len(), "stragglers post-SIGTERM, escalando a SIGKILL");
|
||||
for pid in &stragglers {
|
||||
let _ = kill(*pid, Signal::SIGKILL);
|
||||
}
|
||||
loop {
|
||||
match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
|
||||
Ok(WaitStatus::Exited(pid, _)) | Ok(WaitStatus::Signaled(pid, _, _)) => {
|
||||
self.reap_during_shutdown(pid);
|
||||
}
|
||||
Ok(WaitStatus::StillAlive) => {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
Err(Errno::ECHILD) => break,
|
||||
_ => break,
|
||||
}
|
||||
if !self.incarnated.values().any(|i| i.pid.is_some()) { break; }
|
||||
}
|
||||
info!("cascade shutdown completo (con SIGKILL)");
|
||||
}
|
||||
|
||||
fn reap_during_shutdown(&mut self, pid: Pid) {
|
||||
let Some(id) = self.by_pid.remove(&pid.as_raw()) else { return };
|
||||
if let Some(inc) = self.incarnated.remove(&id) {
|
||||
self.unregister_provider(&inc.card);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Topología del fractal: índice de hijos por lineage y orden topológico
|
||||
//! para shutdown.
|
||||
|
||||
use super::EnteGraph;
|
||||
use std::collections::BTreeSet;
|
||||
use ulid::Ulid;
|
||||
|
||||
impl EnteGraph {
|
||||
/// DFS post-order desde la Semilla. Hojas primero, raíz al final.
|
||||
/// Garantiza que SIGTERM va a un padre sólo cuando sus hijos ya recibieron
|
||||
/// la señal (evita orfandad transitoria que confunda Restart supervisors).
|
||||
pub(in crate::graph) fn topo_order(&self) -> Vec<Ulid> {
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut order = Vec::new();
|
||||
self.dfs_post(self.seed.id, &mut visited, &mut order);
|
||||
// Entes encarnados sin lineage hacia el seed (no debería pasar pero
|
||||
// protege contra grafos huérfanos): añadirlos al final.
|
||||
for id in self.incarnated.keys() {
|
||||
if !visited.contains(id) {
|
||||
self.dfs_post(*id, &mut visited, &mut order);
|
||||
}
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
fn dfs_post(&self, node: Ulid, visited: &mut BTreeSet<Ulid>, order: &mut Vec<Ulid>) {
|
||||
if !visited.insert(node) { return; }
|
||||
if let Some(children) = self.children.get(&node) {
|
||||
for c in children.clone() {
|
||||
self.dfs_post(c, visited, order);
|
||||
}
|
||||
}
|
||||
order.push(node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
//! Ente #0 — el primer Ente. PID 1 del fractal.
|
||||
//!
|
||||
//! Reglas no negociables:
|
||||
//! 1. NUNCA lógica de servicio aquí. Sólo: leer Semilla, cosechar zombis,
|
||||
//! mediar capacidades, propagar eventos.
|
||||
//! 2. Single-threaded. Cualquier paralelismo se delega a Entes worker.
|
||||
//! Un panic en un thread de PID 1 = kernel panic.
|
||||
//! 3. Errores de hijos son *eventos* en `graph_tx`, no `Result` propagado.
|
||||
//!
|
||||
//! Este archivo es sólo wireup. La lógica vive en:
|
||||
//! - `seed` : construcción/restauración de la Tarjeta Semilla
|
||||
//! - `bus` : listener Unix + auth via SO_PEERCRED
|
||||
//! - `graph::*` : estado del fractal (lifecycle, topology, shutdown,
|
||||
//! bus_mediator, devices, capabilities)
|
||||
//! - `events` : tipos de eventos del bucle primordial
|
||||
//! - crates externos del workspace para CAS, soma, wasm, snapshot, kernel.
|
||||
|
||||
mod brain_glue;
|
||||
mod bus;
|
||||
mod events;
|
||||
mod graph;
|
||||
mod seed;
|
||||
|
||||
use anyhow::Context;
|
||||
use ente_brain::{BrainState, IntrospectServer};
|
||||
use ente_kernel::{become_child_subreaper, bootstrap_kernel_surface, spawn_sigchld_stream, spawn_uevent_stream};
|
||||
use events::{ExitStatus, GraphEvent, ShutdownReason};
|
||||
use graph::EnteGraph;
|
||||
use nix::errno::Errno;
|
||||
use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
|
||||
use nix::unistd::{getpid, Pid};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
struct CliArgs {
|
||||
checkpoint: Option<PathBuf>,
|
||||
restore: Option<PathBuf>,
|
||||
rules: Option<PathBuf>,
|
||||
rules_out: Option<PathBuf>,
|
||||
audit_head: Option<PathBuf>,
|
||||
metrics_addr: Option<String>,
|
||||
brain_half_life: Option<f64>,
|
||||
autopromote_secs: Option<u64>,
|
||||
}
|
||||
|
||||
fn parse_args() -> CliArgs {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mut checkpoint = None;
|
||||
let mut restore = None;
|
||||
let mut rules = None;
|
||||
let mut rules_out = None;
|
||||
let mut audit_head = None;
|
||||
let mut metrics_addr = None;
|
||||
let mut brain_half_life = None;
|
||||
let mut autopromote_secs = None;
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--checkpoint" => checkpoint = args.next().map(PathBuf::from),
|
||||
"--restore" => restore = args.next().map(PathBuf::from),
|
||||
"--rules" => rules = args.next().map(PathBuf::from),
|
||||
"--rules-out" => rules_out = args.next().map(PathBuf::from),
|
||||
"--audit-head" => audit_head = args.next().map(PathBuf::from),
|
||||
"--metrics-addr" => metrics_addr = args.next(),
|
||||
"--brain-half-life" => brain_half_life = args.next().and_then(|s| s.parse().ok()),
|
||||
"--autopromote-secs" => autopromote_secs = args.next().and_then(|s| s.parse().ok()),
|
||||
other => warn!(arg = %other, "argumento desconocido, ignorado"),
|
||||
}
|
||||
}
|
||||
CliArgs {
|
||||
checkpoint, restore, rules, rules_out, audit_head,
|
||||
metrics_addr, brain_half_life, autopromote_secs,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
let cli = parse_args();
|
||||
let pid = getpid();
|
||||
let dev_mode = pid != Pid::from_raw(1);
|
||||
|
||||
if dev_mode {
|
||||
warn!(?pid, "ente-zero corriendo en DEV MODE (no PID 1) — kernel surface no se monta");
|
||||
} else {
|
||||
info!("ente-zero despierta como PID 1");
|
||||
bootstrap_kernel_surface().context("bootstrap kernel surface")?;
|
||||
become_child_subreaper().context("PR_SET_CHILD_SUBREAPER")?;
|
||||
}
|
||||
|
||||
let card = seed::load(dev_mode, cli.restore.as_deref())?;
|
||||
|
||||
// current_thread runtime: ver doctrina al inicio del módulo.
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()?;
|
||||
|
||||
rt.block_on(primordial_loop(
|
||||
card, dev_mode,
|
||||
cli.checkpoint, cli.restore, cli.rules, cli.rules_out,
|
||||
cli.audit_head, cli.metrics_addr, cli.brain_half_life,
|
||||
cli.autopromote_secs,
|
||||
))
|
||||
}
|
||||
|
||||
async fn primordial_loop(
|
||||
seed_card: ente_card::EntityCard,
|
||||
dev_mode: bool,
|
||||
checkpoint_path: Option<PathBuf>,
|
||||
restore_path: Option<PathBuf>,
|
||||
rules_path: Option<PathBuf>,
|
||||
rules_out: Option<PathBuf>,
|
||||
audit_head: Option<PathBuf>,
|
||||
metrics_addr: Option<String>,
|
||||
brain_half_life: Option<f64>,
|
||||
autopromote_secs: Option<u64>,
|
||||
) -> anyhow::Result<()> {
|
||||
info!(seed_id = %seed_card.id, label = %seed_card.label, "Ente #0 entra al bucle primordial");
|
||||
|
||||
let (graph_tx, mut graph_rx) = mpsc::channel::<GraphEvent>(64);
|
||||
let mut sigchld = spawn_sigchld_stream()?;
|
||||
// Uevents puede fallar en dev (sin CAP_NET_ADMIN). Degradamos a un
|
||||
// canal nunca-listo en lugar de abortar el bucle primordial.
|
||||
let mut uevents = match spawn_uevent_stream() {
|
||||
Ok(rx) => rx,
|
||||
Err(e) => {
|
||||
warn!(?e, "uevents deshabilitados (probablemente falta CAP_NET_ADMIN)");
|
||||
let (_keep_tx, rx) = mpsc::channel::<ente_kernel::UEvent>(1);
|
||||
std::mem::forget(_keep_tx);
|
||||
rx
|
||||
}
|
||||
};
|
||||
|
||||
// Bus interno: listener antes de spawn de hijos para que su Announce
|
||||
// tenga adónde llegar. Su path se inyecta en ENTE_BUS_SOCK por soma.
|
||||
let bus_sock = bus::default_socket_path();
|
||||
let bus_path = bus::spawn_bus(bus_sock, graph_tx.clone())?;
|
||||
ente_soma::set_bus_sock(bus_path.to_string_lossy().into_owned());
|
||||
|
||||
let mut graph = EnteGraph::new(seed_card);
|
||||
graph.instantiate_seed_dependencies(&graph_tx).await?;
|
||||
|
||||
// Cerebro: BrainState compartido + servidor de introspección.
|
||||
// Window de 1024 eventos — suficiente para correlaciones interesantes
|
||||
// sin gastar memoria de PID 1. En dev bajamos el umbral de cristalización
|
||||
// para que el demo (pocos eventos) produzca cristales observables.
|
||||
let mut brain = if dev_mode {
|
||||
// Umbrales relajados para que el demo (pocos eventos) produzca
|
||||
// cristales observables. Con P(b|a) normalizada a [0,1], los
|
||||
// valores típicos en muestras pequeñas son 0.2-0.5.
|
||||
BrainState::with_params(1024, ente_brain::CrystallizationParams {
|
||||
min_support: 2,
|
||||
min_conditional_prob: 0.3,
|
||||
min_pmi: 1.0,
|
||||
})
|
||||
} else {
|
||||
BrainState::new(1024)
|
||||
};
|
||||
if let Some(out_path) = rules_out {
|
||||
brain = brain.with_rules_out(out_path);
|
||||
}
|
||||
if let Some(hl) = brain_half_life {
|
||||
let mut obs = brain.observer.write().await;
|
||||
// Reemplazar con un observer nuevo que tenga half-life. Estado
|
||||
// anterior (vacío en este punto) descartado.
|
||||
*obs = ente_brain::Observer::new(1024).with_half_life(hl);
|
||||
info!(hl_secs = hl, "observer con time-decay activo");
|
||||
}
|
||||
if let Some(secs) = autopromote_secs {
|
||||
ente_brain::spawn_autopromote_loop(
|
||||
brain.clone(),
|
||||
ente_brain::AutopromoteParams {
|
||||
interval_secs: secs,
|
||||
threshold: brain.params, // mismo threshold que crystals manuales
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Brain restore: si hay --restore <path>, cargamos el snapshot adjunto
|
||||
// <path>.brain.json. Counters preservados across reboots.
|
||||
if let Some(rpath) = &restore_path {
|
||||
let brain_path = rpath.with_extension("brain.json");
|
||||
if brain_path.exists() {
|
||||
match read_brain_snapshot(&brain_path) {
|
||||
Ok(snap) => {
|
||||
let total = snap.total;
|
||||
let kinds = snap.marginal.len();
|
||||
let restored = ente_brain::Observer::from_snapshot(snap);
|
||||
*brain.observer.write().await = restored;
|
||||
info!(
|
||||
path = %brain_path.display(),
|
||||
total, kinds,
|
||||
"brain snapshot restaurado"
|
||||
);
|
||||
}
|
||||
Err(e) => warn!(?e, path = %brain_path.display(), "brain snapshot read falló"),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Si --audit-head, configuramos el head pointer y arrancamos auto-flush.
|
||||
if let Some(head_path) = audit_head {
|
||||
// Re-creamos el AuditLog con head pointer.
|
||||
let new_audit = ente_brain::audit::AuditLog::new()
|
||||
.with_head_pointer(head_path);
|
||||
*brain.audit.write().await = new_audit;
|
||||
spawn_audit_auto_flush(brain.clone());
|
||||
}
|
||||
|
||||
// Carga inicial de reglas desde JSON/JSONL si --rules path proporcionado.
|
||||
if let Some(path) = &rules_path {
|
||||
match ente_brain::load_rules_file(path) {
|
||||
Ok(rules) => {
|
||||
let mut engine = brain.engine.write().await;
|
||||
for r in rules {
|
||||
engine.insert(r);
|
||||
}
|
||||
info!(count = engine.len(), path = %path.display(), "reglas cargadas");
|
||||
}
|
||||
Err(e) => warn!(?e, path = %path.display(), "carga de reglas falló"),
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint Prometheus opcional. En dev por defecto en 127.0.0.1:9911 si
|
||||
// el flag no se pasó.
|
||||
let metrics_addr = metrics_addr.or_else(|| {
|
||||
if dev_mode { Some("127.0.0.1:9911".to_string()) } else { None }
|
||||
});
|
||||
if let Some(addr_s) = metrics_addr {
|
||||
match addr_s.parse::<std::net::SocketAddr>() {
|
||||
Ok(addr) => {
|
||||
let s = brain.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = ente_brain::serve_metrics(s, addr).await {
|
||||
warn!(?e, "metrics server cayó");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => warn!(?e, addr = %addr_s, "metrics-addr inválido"),
|
||||
}
|
||||
}
|
||||
spawn_brain_introspect(brain.clone());
|
||||
let brain_sink = brain_glue::GraphSink {
|
||||
graph_tx: graph_tx.clone(),
|
||||
// Spawns auto-disparados desde reglas usan la identidad de la Semilla
|
||||
// (único Ente con Capability::Spawn por construcción).
|
||||
requester: graph.seed_id(),
|
||||
};
|
||||
|
||||
// Demo automático del forwarding (sólo dev, sólo si el binario existe).
|
||||
if dev_mode && std::path::Path::new("target/debug/ente-echo").exists() {
|
||||
spawn_echo_smoke_test(bus_path.clone());
|
||||
}
|
||||
|
||||
// En dev mode no tenemos hijos por defecto y el bucle se quedaría inerte.
|
||||
let dev_exit = if dev_mode {
|
||||
Some(tokio::time::sleep(Duration::from_secs(4)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
tokio::pin!(dev_exit);
|
||||
|
||||
// GC de capability grants expirados — corre cada 10 segundos.
|
||||
let mut grant_purge = tokio::time::interval(Duration::from_secs(10));
|
||||
grant_purge.tick().await; // descartar primer tick inmediato
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
|
||||
Some(_) = sigchld.recv() => {
|
||||
reap_until_empty(&mut graph, &graph_tx).await;
|
||||
}
|
||||
|
||||
Some(uevt) = uevents.recv() => {
|
||||
graph.on_uevent(uevt, &graph_tx).await;
|
||||
}
|
||||
|
||||
Some(evt) = graph_rx.recv() => {
|
||||
// Cerebro observa antes que el grafo mute. Snapshot del
|
||||
// SubjectInfo se hace contra el estado pre-mutación.
|
||||
feed_brain(&brain, &brain_sink, &graph, &evt).await;
|
||||
if dispatch_graph_event(&mut graph, evt, &graph_tx, &checkpoint_path, &brain).await {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
_ = grant_purge.tick() => {
|
||||
let n = graph.purge_expired_grants();
|
||||
if n > 0 {
|
||||
info!(purged = n, active = graph.active_grants_count(), "GC capability grants");
|
||||
}
|
||||
}
|
||||
|
||||
_ = async { dev_exit.as_mut().as_pin_mut().unwrap().await }, if dev_mode => {
|
||||
info!("dev mode: timer expirado, cerrando bucle primordial");
|
||||
let _ = graph_tx.send(GraphEvent::Shutdown {
|
||||
reason: ShutdownReason::SeedRequested,
|
||||
}).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve `true` si el bucle primordial debe terminar.
|
||||
async fn dispatch_graph_event(
|
||||
graph: &mut EnteGraph,
|
||||
evt: GraphEvent,
|
||||
tx: &mpsc::Sender<GraphEvent>,
|
||||
checkpoint: &Option<PathBuf>,
|
||||
brain: &BrainState,
|
||||
) -> bool {
|
||||
match evt {
|
||||
GraphEvent::EnteDied { id, status } => {
|
||||
graph.on_death(id, status, tx).await;
|
||||
}
|
||||
GraphEvent::CapabilityRequested { from, cap, reply } => {
|
||||
graph.mediate_capability(from, cap, reply).await;
|
||||
}
|
||||
GraphEvent::SpawnRequest { card, requester } => {
|
||||
if let Err(e) = graph.authorize_and_spawn(card, requester).await {
|
||||
warn!(?e, "spawn request error");
|
||||
}
|
||||
}
|
||||
GraphEvent::BusRequest { peer, from, request, outbound, reply } => {
|
||||
graph.on_bus_request(peer, from, request, outbound, reply).await;
|
||||
}
|
||||
GraphEvent::BusResponse { seq, response } => {
|
||||
graph.on_bus_response(seq, response).await;
|
||||
}
|
||||
GraphEvent::BusConnClosed { ente_id } => {
|
||||
graph.on_bus_conn_closed(ente_id).await;
|
||||
}
|
||||
GraphEvent::Shutdown { reason } => {
|
||||
warn!(?reason, "shutdown del fractal");
|
||||
if let Some(path) = checkpoint.as_ref() {
|
||||
// Snapshot del grafo
|
||||
let snap = graph.snapshot();
|
||||
match snap.write(path) {
|
||||
Ok(()) => info!(path = %path.display(), entes = snap.entes.len(), "snapshot fractal persistido"),
|
||||
Err(e) => warn!(?e, "snapshot write falló"),
|
||||
}
|
||||
// Snapshot del cerebro (observer state) en archivo adjunto
|
||||
let brain_path = path.with_extension("brain.json");
|
||||
let obs_snap = brain.observer.write().await.snapshot();
|
||||
match write_brain_snapshot(&brain_path, &obs_snap) {
|
||||
Ok(()) => info!(
|
||||
path = %brain_path.display(),
|
||||
total = obs_snap.total,
|
||||
kinds = obs_snap.marginal.len(),
|
||||
"snapshot brain persistido"
|
||||
),
|
||||
Err(e) => warn!(?e, "brain snapshot write falló"),
|
||||
}
|
||||
}
|
||||
graph.cascade_shutdown().await;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
async fn reap_until_empty(graph: &mut EnteGraph, tx: &mpsc::Sender<GraphEvent>) {
|
||||
loop {
|
||||
match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
|
||||
Ok(WaitStatus::StillAlive) => return,
|
||||
Ok(WaitStatus::Exited(pid, code)) => {
|
||||
emit_death(graph, tx, pid, ExitStatus::Exit(code)).await;
|
||||
}
|
||||
Ok(WaitStatus::Signaled(pid, sig, _core)) => {
|
||||
emit_death(graph, tx, pid, ExitStatus::Killed(sig)).await;
|
||||
}
|
||||
Ok(_) => continue, // Stopped/Continued — irrelevantes
|
||||
Err(Errno::ECHILD) => return,
|
||||
Err(e) => {
|
||||
error!(?e, "waitpid fallo no recuperable en bucle de reaping");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn emit_death(
|
||||
graph: &EnteGraph,
|
||||
tx: &mpsc::Sender<GraphEvent>,
|
||||
pid: Pid,
|
||||
status: ExitStatus,
|
||||
) {
|
||||
let id = match graph.lookup_pid(pid) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
// Proceso adoptado (subreaper): no está en nuestro grafo.
|
||||
info!(?pid, ?status, "huérfano cosechado (no en grafo)");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = tx.send(GraphEvent::EnteDied { id, status }).await;
|
||||
}
|
||||
|
||||
fn spawn_echo_smoke_test(bus_path: PathBuf) {
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
match ente_bus::BusClient::connect(&bus_path).await {
|
||||
Ok(mut client) => {
|
||||
let req = ente_bus::BusRequest::Invoke {
|
||||
cap: ente_echo::echo_capability(),
|
||||
blob: b"hola fractal forwardeado".to_vec(),
|
||||
};
|
||||
match client.call(req).await {
|
||||
Ok(ente_bus::BusResponse::Invoked { result }) => {
|
||||
info!(echo = %String::from_utf8_lossy(&result), "Invoke ECHO round-trip OK");
|
||||
}
|
||||
Ok(other) => warn!(?other, "Invoke ECHO respuesta inesperada"),
|
||||
Err(e) => warn!(?e, "Invoke ECHO falló"),
|
||||
}
|
||||
}
|
||||
Err(e) => warn!(?e, "no se pudo conectar al bus para test"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn write_brain_snapshot(path: &std::path::Path, snap: &ente_brain::observer::ObserverSnapshot) -> anyhow::Result<()> {
|
||||
let bytes = serde_json::to_vec_pretty(snap)?;
|
||||
if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
let tmp = path.with_extension("tmp");
|
||||
std::fs::write(&tmp, &bytes)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_brain_snapshot(path: &std::path::Path) -> anyhow::Result<ente_brain::observer::ObserverSnapshot> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
let snap: ente_brain::observer::ObserverSnapshot = serde_json::from_slice(&bytes)?;
|
||||
Ok(snap)
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
use tracing_subscriber::{fmt, EnvFilter};
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("ente_zero=debug,info"));
|
||||
fmt().with_env_filter(filter).with_target(true).init();
|
||||
}
|
||||
|
||||
fn brain_introspect_path() -> PathBuf {
|
||||
if let Ok(p) = std::env::var("ENTE_BRAIN_SOCK") {
|
||||
return p.into();
|
||||
}
|
||||
let runtime = std::env::var("XDG_RUNTIME_DIR")
|
||||
.unwrap_or_else(|_| std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()));
|
||||
format!("{runtime}/ente-brain.sock").into()
|
||||
}
|
||||
|
||||
/// Auto-flush del audit log a CAS cada 10 segundos. Ejecuta best-effort:
|
||||
/// si el flush falla lo logeamos pero no abortamos. La integridad del log
|
||||
/// queda garantizada por su hash chain — re-flushar es idempotente.
|
||||
fn spawn_audit_auto_flush(state: BrainState) {
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(std::time::Duration::from_secs(10));
|
||||
tick.tick().await; // descartar primer tick inmediato
|
||||
loop {
|
||||
tick.tick().await;
|
||||
let mut audit = state.audit.write().await;
|
||||
match audit.flush_to_cas() {
|
||||
Ok(0) => {} // nada nuevo
|
||||
Ok(n) => info!(written = n, total = audit.flushed_count(), "audit auto-flush"),
|
||||
Err(e) => warn!(?e, "audit auto-flush falló"),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_brain_introspect(state: BrainState) {
|
||||
let path = brain_introspect_path();
|
||||
tokio::spawn(async move {
|
||||
let server = IntrospectServer::new(state);
|
||||
if let Err(e) = server.serve(&path).await {
|
||||
warn!(?e, "introspect server cayó");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Registra el evento en el observer y dispatcha cualquier regla matched.
|
||||
/// Para reglas Sequence: pasamos los últimos N eventos del observer como
|
||||
/// history al engine.
|
||||
async fn feed_brain(
|
||||
brain: &BrainState,
|
||||
sink: &brain_glue::GraphSink,
|
||||
graph: &EnteGraph,
|
||||
evt: &GraphEvent,
|
||||
) {
|
||||
let Some((kind, subj)) = brain_glue::graph_event_to_brain(evt, graph) else { return };
|
||||
let history: Vec<ente_brain::TimedEvent> = {
|
||||
let mut obs = brain.observer.write().await;
|
||||
obs.record(kind.clone());
|
||||
// Snapshot de los últimos 16 eventos — suficiente para cualquier
|
||||
// Sequence pattern razonable. Clone hace una sola alocación.
|
||||
obs.recent(16).cloned().collect()
|
||||
};
|
||||
let rules = {
|
||||
let engine = brain.engine.read().await;
|
||||
engine.dispatch(&kind, &subj, &history)
|
||||
};
|
||||
if !rules.is_empty() {
|
||||
ente_brain::dispatch_actions(&rules, sink).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Construcción de la Tarjeta Semilla.
|
||||
//!
|
||||
//! Tres caminos:
|
||||
//! 1. `--restore <path>`: leer `FractalSnapshot` y reconstruir Semilla
|
||||
//! con seed_id preservado + entes anteriores como genesis.
|
||||
//! 2. `seed.card.json` en disco: deserialize directo (prod o dev).
|
||||
//! 3. Fallback dev: sintetizar Semilla + 6 genesis Entes que ejercitan
|
||||
//! todas las capacidades del fractal.
|
||||
|
||||
use anyhow::Context;
|
||||
use ente_card::{
|
||||
Capability, CardError, CgroupSpec, EntityCard, NamespaceSet, Payload,
|
||||
ResourceLimits, SomaSpec, Supervision, CARD_SCHEMA_VERSION,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use tracing::{info, warn};
|
||||
use ulid::Ulid;
|
||||
|
||||
const SEED_PATH_PROD: &str = "/ente/seed.card";
|
||||
const SEED_PATH_DEV: &str = "seed.card";
|
||||
|
||||
pub fn load(dev_mode: bool, restore: Option<&Path>) -> anyhow::Result<EntityCard> {
|
||||
let card = if let Some(path) = restore {
|
||||
load_from_snapshot(path)?
|
||||
} else {
|
||||
load_or_synthesize(dev_mode)?
|
||||
};
|
||||
card.validate()
|
||||
.map_err(|e: CardError| anyhow::anyhow!("semilla inválida: {e}"))?;
|
||||
Ok(card)
|
||||
}
|
||||
|
||||
fn load_from_snapshot(path: &Path) -> anyhow::Result<EntityCard> {
|
||||
let snap = ente_snapshot::FractalSnapshot::read(path)
|
||||
.with_context(|| format!("read snapshot {}", path.display()))?;
|
||||
info!(
|
||||
path = %path.display(),
|
||||
seed_id = %snap.seed_id,
|
||||
entes = snap.entes.len(),
|
||||
timestamp_ms = snap.timestamp_ms,
|
||||
"snapshot cargado, restaurando fractal"
|
||||
);
|
||||
// Reconstruimos la Semilla con su Ulid original. Las Cards persistidas
|
||||
// van a `genesis` con sus Ulids preservados — son las mismas identidades
|
||||
// que vivieron antes del checkpoint.
|
||||
let mut provides = BTreeSet::new();
|
||||
provides.insert(Capability::Spawn);
|
||||
provides.insert(Capability::Journal);
|
||||
Ok(EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: snap.seed_id,
|
||||
lineage: None,
|
||||
label: snap.seed_label,
|
||||
provides,
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec::default(),
|
||||
payload: Payload::Virtual,
|
||||
supervision: Supervision::OneShot,
|
||||
genesis: snap.entes,
|
||||
})
|
||||
}
|
||||
|
||||
fn load_or_synthesize(dev_mode: bool) -> anyhow::Result<EntityCard> {
|
||||
// Buscamos primero `.json` (canónico), luego sin extensión por
|
||||
// compatibilidad con instalaciones que dejan el archivo crudo. La puerta
|
||||
// genética se cruza vía `ente_brain::load_card_file` que pasa por
|
||||
// `validate()` extendido.
|
||||
let candidates: &[&str] = if dev_mode {
|
||||
&["seed.card.json", SEED_PATH_DEV]
|
||||
} else {
|
||||
&["/ente/seed.card.json", SEED_PATH_PROD]
|
||||
};
|
||||
for cand in candidates {
|
||||
let path = PathBuf::from(cand);
|
||||
if !path.exists() { continue; }
|
||||
let card = ente_brain::load_card_file(&path)
|
||||
.with_context(|| format!("load {}", path.display()))?;
|
||||
info!(path = %path.display(), "Tarjeta Semilla cargada y validada");
|
||||
return Ok(card);
|
||||
}
|
||||
if dev_mode {
|
||||
info!("sin seed.card — sintetizando semilla mínima (dev)");
|
||||
return Ok(synthesize_dev_seed());
|
||||
}
|
||||
anyhow::bail!("seed.card no encontrada en /ente/seed.card.json ni /ente/seed.card")
|
||||
}
|
||||
|
||||
fn synthesize_dev_seed() -> EntityCard {
|
||||
let mut provides = BTreeSet::new();
|
||||
provides.insert(Capability::Spawn);
|
||||
provides.insert(Capability::Journal);
|
||||
|
||||
// Pre-registramos el módulo Wasm demo en el CAS y obtenemos su SHA real.
|
||||
// Si el CAS no es escribible (raro en dev) caemos a un SHA cero — la
|
||||
// resolución fallará y el Wasm no encarnará, pero el resto queda intacto.
|
||||
let demo_wasm_sha = match ente_wasm::demo_module_bytes()
|
||||
.and_then(|b| ente_cas::store(&b))
|
||||
{
|
||||
Ok(sha) => sha,
|
||||
Err(e) => {
|
||||
warn!(?e, "CAS no disponible — demo-wasm no encarnará");
|
||||
[0u8; 32]
|
||||
}
|
||||
};
|
||||
|
||||
let mut genesis = Vec::new();
|
||||
genesis.push(make_card("demo-sleep", Payload::Native {
|
||||
exec: "/bin/sleep".into(), argv: vec!["1".into()], envp: vec![],
|
||||
}, Supervision::OneShot));
|
||||
|
||||
genesis.push(make_card("demo-persist", Payload::Native {
|
||||
exec: "/bin/sleep".into(), argv: vec!["60".into()], envp: vec![],
|
||||
}, restart_supervision()));
|
||||
|
||||
// Card namespaced: padre escribe uid_map, hijo cat /proc/self/uid_map.
|
||||
let mut ns_card = make_card("demo-userns", Payload::Native {
|
||||
exec: "/bin/cat".into(),
|
||||
argv: vec!["/proc/self/uid_map".into()],
|
||||
envp: vec![],
|
||||
}, Supervision::OneShot);
|
||||
ns_card.soma = SomaSpec {
|
||||
namespaces: NamespaceSet { user: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
genesis.push(ns_card);
|
||||
|
||||
genesis.push(make_card("demo-wasm", Payload::Wasm {
|
||||
module_sha256: demo_wasm_sha,
|
||||
entry: "_start".into(),
|
||||
}, Supervision::OneShot));
|
||||
|
||||
if let Some(card) = optional_native_card(
|
||||
"demo-echo", "target/debug/ente-echo",
|
||||
[ente_echo::echo_capability()].into_iter().collect(),
|
||||
restart_supervision(),
|
||||
) {
|
||||
genesis.push(card);
|
||||
}
|
||||
|
||||
if let Some(card) = optional_native_card(
|
||||
"compat-logind", "target/debug/ente-logind-compat",
|
||||
[Capability::LegacyLogind].into_iter().collect(),
|
||||
restart_supervision(),
|
||||
) {
|
||||
genesis.push(card);
|
||||
}
|
||||
|
||||
// Constelación de shims D-Bus que reemplazan systemd: cada uno provee
|
||||
// un nombre `org.freedesktop.X1` que GNOME/KDE consultan al boot.
|
||||
for (label, bin) in &[
|
||||
("compat-hostnamed", "target/debug/ente-hostnamed-compat"),
|
||||
("compat-timedated", "target/debug/ente-timedated-compat"),
|
||||
("compat-localed", "target/debug/ente-localed-compat"),
|
||||
("compat-journald", "target/debug/ente-journald-compat"),
|
||||
("compat-resolved", "target/debug/ente-resolved-compat"),
|
||||
("compat-polkit", "target/debug/ente-polkit-compat"),
|
||||
("compat-machined", "target/debug/ente-machined-compat"),
|
||||
("policy-provider", "target/debug/ente-policy-provider"),
|
||||
("compat-systemd1", "target/debug/ente-systemd1-compat"),
|
||||
("compat-notify", "target/debug/ente-notify-compat"),
|
||||
("compat-timer", "target/debug/ente-timer-compat"),
|
||||
] {
|
||||
if let Some(card) = optional_native_card(
|
||||
label, bin,
|
||||
std::collections::BTreeSet::new(),
|
||||
restart_supervision(),
|
||||
) {
|
||||
genesis.push(card);
|
||||
}
|
||||
}
|
||||
|
||||
EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: "ente-zero-dev".into(),
|
||||
provides,
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec {
|
||||
namespaces: NamespaceSet::default(),
|
||||
rlimits: ResourceLimits::default(),
|
||||
cgroup: CgroupSpec {
|
||||
path: "ente.slice/zero".into(),
|
||||
cpu_weight: None,
|
||||
io_weight: None,
|
||||
},
|
||||
cpu_affinity: None,
|
||||
},
|
||||
payload: Payload::Virtual,
|
||||
supervision: Supervision::OneShot,
|
||||
genesis,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_card(label: &str, payload: Payload, supervision: Supervision) -> EntityCard {
|
||||
EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: label.into(),
|
||||
provides: BTreeSet::new(),
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec::default(),
|
||||
payload,
|
||||
supervision,
|
||||
genesis: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_native_card(
|
||||
label: &str,
|
||||
bin_path: &str,
|
||||
provides: BTreeSet<Capability>,
|
||||
supervision: Supervision,
|
||||
) -> Option<EntityCard> {
|
||||
let path = Path::new(bin_path);
|
||||
if !path.exists() {
|
||||
return None;
|
||||
}
|
||||
Some(EntityCard {
|
||||
schema_version: CARD_SCHEMA_VERSION,
|
||||
id: Ulid::new(),
|
||||
lineage: None,
|
||||
label: label.into(),
|
||||
provides,
|
||||
requires: BTreeSet::new(),
|
||||
soma: SomaSpec::default(),
|
||||
payload: Payload::Native {
|
||||
exec: path.to_string_lossy().into_owned(),
|
||||
argv: vec![],
|
||||
envp: vec![],
|
||||
},
|
||||
supervision,
|
||||
genesis: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
fn restart_supervision() -> Supervision {
|
||||
Supervision::Restart {
|
||||
initial: Duration::from_millis(100),
|
||||
max: Duration::from_secs(30),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user