refactor(naming): A1 — ente→arje, vista→revista, pluma→fana
Rename batch de la Fase A del PLAN_MACRO: - 25 crates ente-* → arje-* (protocol/init/runtime/compat). El linaje arje (init Linux) queda con prefijo coherente. - vista → revista (revista-core + revista-web). - pluma → fana (fana-md + fana-md-reader-web). fana absorbe el linaje markdown de pluma; será el writer DAG editor (prioridad alta). Cambios: - git mv de 29 crate dirs + 2 SDDs - package/lib/bin names + path refs + imports .rs reescritos - workspace Cargo.toml + comentarios de sección - SDDs de init/runtime/compat/protocol actualizados a arje- - SDD de revista + SDD de fana (reescrito: writer DAG editor) - docs/STATUS.md, ROADMAP.md, PLAN_MACRO.md, arje-boot.md, arje-replace-systemd.md actualizados - docs/changelog/akasha.md → chasqui.md scripts/rename-fase-a.py idempotente (--dry-run soportado). cargo check --workspace verde. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -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,85 @@
|
||||
//! 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 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 arje_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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user