phoebus_os/installer-rs/crates/phoebus-executor/src/log.rs
Phoebus b4a6b5df80
Some checks are pending
ci / test (push) Waiting to run
feat(nvidia): hardware-driven driver policy, installed integration and live payload
- resolve the NVIDIA branch and kernel-module flavor from PCI device IDs
  (Turing+ open modules; Maxwell/Pascal/Volta proprietary, masked below 595;
  Fermi/Kepler fall back to nouveau, reported; unknown IDs reported)
- capture pci_id/pci_address in the probe; drive VIDEO_CARDS, package.use,
  package.accept_keywords, package.mask, modprobe.d and dracut from the plan,
  preserving hybrid Intel/AMD
- add the nvidia_drivers install stage (after the kernel, before boot) that
  emerges the driver, regenerates the initramfs, records /etc/phoebus/nvidia and
  fails the install on failure; sys update rebuilds modules and the initramfs
- refuse AI changes to x11-drivers/nvidia-drivers
- live ISO: signed non-free components, stable-kernel pin (testing 7.2 breaks
  the 550 driver), DKMS build for the exact kernel, gated pre-greetd load,
  fail-safe entry, gpu-report, and a --verify-live-nvidia build gate that runs
  on cached rootfs builds and fails on any missing component
- docs: ADR 0012, STATUS/CHANGELOG/HANDOFF, live README
- also carries the pending OpenCode model-variant/streaming changes and fixes
  the GUI bridge install thread join that could hang
2026-09-22 21:53:28 -07:00

308 lines
9 KiB
Rust

//! Installer logging with mandatory secret redaction.
//!
//! Every log line is passed through the shared `Redactor`, so a caller cannot
//! accidentally write a registered secret. Command output is captured and
//! logged through the same path.
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use phoebus_core::Redactor;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
Debug,
Info,
Warn,
Error,
}
impl Level {
fn as_str(self) -> &'static str {
match self {
Level::Debug => "DEBUG",
Level::Info => "INFO",
Level::Warn => "WARN",
Level::Error => "ERROR",
}
}
}
use std::sync::Arc;
pub type LogListener = Arc<dyn Fn(&str) + Send + Sync>;
struct LoggerInner {
path: PathBuf,
file: Mutex<Option<File>>,
echo: bool,
redactor: Redactor,
listeners: Mutex<Vec<LogListener>>,
}
#[derive(Clone)]
pub struct Logger {
inner: Arc<LoggerInner>,
}
impl Logger {
/// Open (or create) the log file. Falls back to an in-memory logger when
/// the path cannot be opened, so logging never aborts the installer.
pub fn open(path: impl Into<PathBuf>, redactor: Redactor, echo: bool) -> Self {
let path = path.into();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.ok();
Self {
inner: Arc::new(LoggerInner {
path,
file: Mutex::new(file),
echo,
redactor,
listeners: Mutex::new(Vec::new()),
}),
}
}
pub fn path(&self) -> &Path {
&self.inner.path
}
pub fn redactor(&self) -> &Redactor {
&self.inner.redactor
}
pub fn register_secret(&self, secret: &phoebus_core::SecretString) {
self.inner.redactor.register(secret);
}
pub fn add_listener(&self, listener: LogListener) {
if let Ok(mut listeners) = self.inner.listeners.lock() {
listeners.push(listener);
}
}
pub fn clear_listeners(&self) {
if let Ok(mut listeners) = self.inner.listeners.lock() {
listeners.clear();
}
}
fn write_line(&self, level: Level, message: &str) {
let message = self.inner.redactor.redact(message);
let line = format!("{} [{}] {}\n", timestamp(), level.as_str(), message);
if let Ok(mut guard) = self.inner.file.lock() {
if let Some(file) = guard.as_mut() {
let _ = file.write_all(line.as_bytes());
let _ = file.flush();
}
}
if self.inner.echo {
let _ = std::io::stderr().write_all(line.as_bytes());
}
if let Ok(listeners) = self.inner.listeners.lock() {
for listener in listeners.iter() {
listener(&line);
}
}
}
pub fn debug(&self, message: impl AsRef<str>) {
self.write_line(Level::Debug, message.as_ref());
}
pub fn info(&self, message: impl AsRef<str>) {
self.write_line(Level::Info, message.as_ref());
}
pub fn warn(&self, message: impl AsRef<str>) {
self.write_line(Level::Warn, message.as_ref());
}
pub fn error(&self, message: impl AsRef<str>) {
self.write_line(Level::Error, message.as_ref());
}
pub fn section(&self, name: &str) {
self.write_line(Level::Info, &format!("--- {name} ---"));
}
/// Log the start of a command before running it.
pub fn command_start(
&self,
stage: &str,
operation: &str,
program: &str,
args: &[String],
stdin_hidden: bool,
) {
let mut line = format!("[{stage}] {operation} :: {program}");
for arg in args {
line.push(' ');
line.push_str(&shell_quote(arg));
}
if stdin_hidden {
line.push_str(" (stdin hidden)");
}
self.write_line(Level::Info, &line);
}
/// Log a command with its exit status and duration (all redacted).
pub fn command(
&self,
stage: &str,
operation: &str,
program: &str,
args: &[String],
status: i32,
duration: Duration,
stdin_hidden: bool,
) {
let mut line = format!("[{stage}] {operation} :: {program}");
for arg in args {
line.push(' ');
line.push_str(&shell_quote(arg));
}
if stdin_hidden {
line.push_str(" (stdin hidden)");
}
line.push_str(&format!(
" :: exit {status} in {:.3}s",
duration.as_secs_f64()
));
self.write_line(Level::Info, &line);
}
/// Append streaming command output to the log in real time, redacted.
pub fn stream_output(&self, text: &str) {
if text.is_empty() {
return;
}
let redacted = self.inner.redactor.redact(text);
if let Ok(mut guard) = self.inner.file.lock() {
if let Some(file) = guard.as_mut() {
let _ = file.write_all(redacted.as_bytes());
if !redacted.ends_with('\n') {
let _ = file.write_all(b"\n");
}
let _ = file.flush();
}
}
if self.inner.echo {
let _ = std::io::stderr().write_all(redacted.as_bytes());
}
if let Ok(listeners) = self.inner.listeners.lock() {
for listener in listeners.iter() {
listener(&redacted);
}
}
}
/// Append raw command output (stdout/stderr) to the log, redacted.
pub fn output(&self, bytes: &[u8]) {
if bytes.is_empty() {
return;
}
let text = String::from_utf8_lossy(bytes);
self.stream_output(&text);
}
pub fn dry_run(&self, stage: &str, operation: &str, program: &str, args: &[String]) {
let mut line = format!("[{stage}] [dry-run] {operation} :: {program}");
for arg in args {
line.push(' ');
line.push_str(&shell_quote(arg));
}
self.write_line(Level::Info, &line);
}
}
fn shell_quote(arg: &str) -> String {
if arg
.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_./:=,@+".contains(c))
{
arg.to_string()
} else {
format!("'{}'", arg.replace('\'', "'\\''"))
}
}
/// Minimal UTC timestamp without pulling in a date crate.
fn timestamp() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let secs = now.as_secs() as i64;
let millis = now.subsec_millis();
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{millis:03}Z")
}
/// Howard Hinnant's civil-from-days algorithm.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + 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;
(if m <= 2 { y + 1 } else { y }, m, d)
}
#[cfg(test)]
mod tests {
use super::*;
use phoebus_core::SecretString;
#[test]
fn secrets_are_redacted_in_log_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("install.log");
let redactor = Redactor::new();
let secret = SecretString::new("hunter2");
redactor.register(&secret);
let logger = Logger::open(&path, redactor, false);
logger.info("passphrase is hunter2 here");
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("<redacted>"));
assert!(!text.contains("hunter2"));
}
#[test]
fn command_logging_includes_stage_and_status() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("install.log");
let logger = Logger::open(&path, Redactor::new(), false);
logger.command(
"storage_prepare",
"create GPT",
"sgdisk",
&["--zap-all".into(), "/dev/vda".into()],
0,
Duration::from_millis(12),
false,
);
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("[storage_prepare] create GPT :: sgdisk"));
assert!(text.contains("/dev/vda"));
assert!(text.contains("exit 0"));
}
#[test]
fn timestamp_has_expected_shape() {
let ts = timestamp();
assert_eq!(ts.len(), 24);
assert!(ts.ends_with('Z'));
}
}