4 D-Bus shims sustituyendo systemd: hostnamed, timedated, localed, journald
Patrón de compat-logind extendido a 4 servicios más que GNOME/KDE consultan al boot. Cada uno: anuncia al bus interno, intenta RequestName en system bus, degrada a idle si la policy lo bloquea, sirve método mientras esté arriba. - compat-hostnamed: org.freedesktop.hostname1. Properties read /etc/hostname, /etc/os-release, /sys/class/dmi/id/* y uname(). Setters log + cache. - compat-timedated: org.freedesktop.timedate1. Timezone via readlink /etc/localtime. ListTimezones desde /usr/share/zoneinfo. - compat-localed: org.freedesktop.locale1. Lee /etc/locale.conf, /etc/vconsole.conf, /etc/X11/xorg.conf.d/00-keyboard.conf. - compat-journald: stub datagram listener en /run/systemd/journal/socket y /dev/log. Decodifica syslog y journald native, emite tracing events. Dev seed los incluye condicionalmente. Verificado: los 5 shims (logind+4 nuevos) anunciados al bus interno con auth SO_PEERCRED. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,166 @@
|
||||
//! 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;
|
||||
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();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
// Heurística: si tiene '=' en alguna línea, asumir journald.
|
||||
if s.contains('=') && s.lines().any(|l| l.contains('=')) {
|
||||
let mut message = None;
|
||||
let mut priority = None;
|
||||
let mut unit = 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()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(msg) = message {
|
||||
info!(target: "journal", source, ?priority, ?unit, "{msg}");
|
||||
} else {
|
||||
debug!(source, len = buf.len(), "journal native sin MESSAGE");
|
||||
}
|
||||
} else {
|
||||
// Syslog
|
||||
info!(target: "syslog", source, "{}", s.trim_end());
|
||||
}
|
||||
} else {
|
||||
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();
|
||||
}
|
||||
Reference in New Issue
Block a user