journal-query CLI, machined, polkit con grants reales, GNOME boot test

- ente-journalctl: bin nuevo en ente-journald-compat. Lee
  ~/.local/share/ente/journal/index.log, parse timestamp:source:unit:sha,
  filtra --unit/--source/--since/--grep/--tail, restituye blobs desde CAS
  y formatea (pretty | --json). Default extrae MESSAGE de journald native.
- compat-machined: org.freedesktop.machine1.Manager con
  ListMachines/GetMachine/Register/Terminate. Lista vacía + NotFound —
  apps que llaman al boot ya no quedan en timeout.
- compat-polkit: query_policy() consulta el bus interno por el cap
  POLKIT_DECISION_IFACE con blob (pid_be|uid_be|action_id_utf8). Si hay
  proveedor su byte de respuesta gobierna; si no, default-allow.
  Anuncia POLKIT_SERVICE_IFACE (separado para evitar recursión).
- docs/gnome-boot-test.md: procedimiento end-to-end para arrancar GNOME
  con ente-zero como PID 1 en QEMU. scripts/build-rootfs.sh overlaya
  binarios + symlink /init. scripts/run-vm.sh boot QEMU con KVM y GTK.
  docs/seed-gnome-test.k Card Semilla con genesis para 8 shims +
  dbus-daemon + NetworkManager + gdm.

8 compat-shims operativos en paralelo cubriendo: logind, hostnamed,
timedated, localed, journald, resolved, polkit, machined.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sergio
2026-05-04 10:13:00 +00:00
parent d88a9c5791
commit 48e41331a1
13 changed files with 959 additions and 6 deletions
@@ -0,0 +1,197 @@
//! 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>,
json: bool,
}
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, json: false,
};
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.json = true,
"-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!(" --json JSON-lines en lugar de pretty");
}
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 {
if args.json {
print_json(&e, &body);
} else {
print_pretty(&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}");
}
}
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
);
}