Some checks are pending
ci / test (push) Waiting to run
- 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
352 lines
9.9 KiB
Rust
352 lines
9.9 KiB
Rust
//! Central command execution layer.
|
|
//!
|
|
//! Arguments stay separate: there is no `sh -c`, no string interpolation into
|
|
//! a shell, and secrets travel only via stdin. The `ProcessRunner` trait lets
|
|
//! privileged logic be tested with a fake runner without touching the system.
|
|
|
|
use std::collections::HashMap;
|
|
use std::io::Write;
|
|
use std::path::PathBuf;
|
|
use std::process::{Command, Stdio};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use crate::error::{ExecError, Result};
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct CommandSpec {
|
|
pub program: String,
|
|
pub args: Vec<String>,
|
|
/// Raw stdin bytes. Never logged. Used for LUKS passphrases and password
|
|
/// hashes.
|
|
pub stdin: Option<Vec<u8>>,
|
|
pub env: Vec<(String, String)>,
|
|
pub cwd: Option<PathBuf>,
|
|
pub stage: String,
|
|
pub operation: String,
|
|
}
|
|
|
|
impl CommandSpec {
|
|
pub fn new(
|
|
stage: impl Into<String>,
|
|
operation: impl Into<String>,
|
|
program: impl Into<String>,
|
|
) -> Self {
|
|
Self {
|
|
program: program.into(),
|
|
args: Vec::new(),
|
|
stdin: None,
|
|
env: Vec::new(),
|
|
cwd: None,
|
|
stage: stage.into(),
|
|
operation: operation.into(),
|
|
}
|
|
}
|
|
|
|
pub fn arg(mut self, arg: impl Into<String>) -> Self {
|
|
self.args.push(arg.into());
|
|
self
|
|
}
|
|
|
|
pub fn args<I, S>(mut self, args: I) -> Self
|
|
where
|
|
I: IntoIterator<Item = S>,
|
|
S: Into<String>,
|
|
{
|
|
self.args.extend(args.into_iter().map(Into::into));
|
|
self
|
|
}
|
|
|
|
pub fn stdin(mut self, bytes: impl Into<Vec<u8>>) -> Self {
|
|
self.stdin = Some(bytes.into());
|
|
self
|
|
}
|
|
|
|
pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
|
self.env.push((key.into(), value.into()));
|
|
self
|
|
}
|
|
|
|
pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
|
|
self.cwd = Some(dir.into());
|
|
self
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct CommandOutput {
|
|
pub status: i32,
|
|
pub success: bool,
|
|
pub stdout: Vec<u8>,
|
|
pub stderr: Vec<u8>,
|
|
pub duration: Duration,
|
|
}
|
|
|
|
impl CommandOutput {
|
|
pub fn dry_run() -> Self {
|
|
Self {
|
|
status: 0,
|
|
success: true,
|
|
stdout: Vec::new(),
|
|
stderr: Vec::new(),
|
|
duration: Duration::ZERO,
|
|
}
|
|
}
|
|
|
|
pub fn stdout_lossy(&self) -> String {
|
|
String::from_utf8_lossy(&self.stdout).into_owned()
|
|
}
|
|
|
|
pub fn stderr_lossy(&self) -> String {
|
|
String::from_utf8_lossy(&self.stderr).into_owned()
|
|
}
|
|
}
|
|
|
|
pub type StreamSink = Arc<dyn Fn(&str) + Send + Sync>;
|
|
|
|
pub trait ProcessRunner: Send + Sync {
|
|
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput>;
|
|
fn is_streaming(&self) -> bool {
|
|
false
|
|
}
|
|
}
|
|
|
|
/// The real process runner.
|
|
#[derive(Clone, Default)]
|
|
pub struct RealRunner {
|
|
sink: Option<StreamSink>,
|
|
}
|
|
|
|
impl RealRunner {
|
|
pub fn new() -> Self {
|
|
Self { sink: None }
|
|
}
|
|
|
|
pub fn with_sink(sink: StreamSink) -> Self {
|
|
Self { sink: Some(sink) }
|
|
}
|
|
}
|
|
|
|
impl ProcessRunner for RealRunner {
|
|
fn is_streaming(&self) -> bool {
|
|
self.sink.is_some()
|
|
}
|
|
|
|
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
|
|
let start = Instant::now();
|
|
let mut command = Command::new(&spec.program);
|
|
command.args(&spec.args);
|
|
for (k, v) in &spec.env {
|
|
command.env(k, v);
|
|
}
|
|
if let Some(cwd) = &spec.cwd {
|
|
command.current_dir(cwd);
|
|
}
|
|
command.stdout(Stdio::piped());
|
|
command.stderr(Stdio::piped());
|
|
command.stdin(if spec.stdin.is_some() {
|
|
Stdio::piped()
|
|
} else {
|
|
Stdio::null()
|
|
});
|
|
|
|
let mut child = command.spawn().map_err(|source| ExecError::Spawn {
|
|
program: spec.program.clone(),
|
|
source,
|
|
})?;
|
|
|
|
if let Some(bytes) = &spec.stdin {
|
|
if let Some(mut stdin) = child.stdin.take() {
|
|
// Ignore broken-pipe style errors; the process exit status is
|
|
// the source of truth.
|
|
let _ = stdin.write_all(bytes);
|
|
let _ = stdin.flush();
|
|
}
|
|
}
|
|
|
|
let mut stdout_pipe = child.stdout.take();
|
|
let mut stderr_pipe = child.stderr.take();
|
|
|
|
let (stdout, stderr) = std::thread::scope(|s| {
|
|
let out_handle = s.spawn(|| {
|
|
let mut captured = Vec::new();
|
|
if let Some(pipe) = stdout_pipe.take() {
|
|
let mut reader = std::io::BufReader::new(pipe);
|
|
let mut buf = Vec::new();
|
|
use std::io::BufRead;
|
|
while let Ok(n) = reader.read_until(b'\n', &mut buf) {
|
|
if n == 0 {
|
|
break;
|
|
}
|
|
captured.extend_from_slice(&buf);
|
|
if let Some(sink) = &self.sink {
|
|
let text = String::from_utf8_lossy(&buf);
|
|
sink(&text);
|
|
}
|
|
buf.clear();
|
|
}
|
|
}
|
|
captured
|
|
});
|
|
|
|
let err_handle = s.spawn(|| {
|
|
let mut captured = Vec::new();
|
|
if let Some(pipe) = stderr_pipe.take() {
|
|
let mut reader = std::io::BufReader::new(pipe);
|
|
let mut buf = Vec::new();
|
|
use std::io::BufRead;
|
|
while let Ok(n) = reader.read_until(b'\n', &mut buf) {
|
|
if n == 0 {
|
|
break;
|
|
}
|
|
captured.extend_from_slice(&buf);
|
|
if let Some(sink) = &self.sink {
|
|
let text = String::from_utf8_lossy(&buf);
|
|
sink(&text);
|
|
}
|
|
buf.clear();
|
|
}
|
|
}
|
|
captured
|
|
});
|
|
|
|
(out_handle.join().unwrap(), err_handle.join().unwrap())
|
|
});
|
|
|
|
let status = child.wait().map_err(|source| ExecError::Spawn {
|
|
program: spec.program.clone(),
|
|
source,
|
|
})?;
|
|
let duration = start.elapsed();
|
|
let code = status.code().unwrap_or(-1);
|
|
Ok(CommandOutput {
|
|
status: code,
|
|
success: status.success(),
|
|
stdout,
|
|
stderr,
|
|
duration,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// A recording runner for tests. It records every spec and returns canned
|
|
/// output per program (or a default success). Cloneable so a test can keep a
|
|
/// handle while the `Exec` owns another.
|
|
#[derive(Clone, Default)]
|
|
pub struct RecordingRunner {
|
|
recorded: Arc<Mutex<Vec<CommandSpec>>>,
|
|
responses: Arc<Mutex<HashMap<String, CommandOutput>>>,
|
|
default: Arc<Mutex<Option<CommandOutput>>>,
|
|
}
|
|
|
|
impl RecordingRunner {
|
|
pub fn new() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
pub fn set_response(&self, program: &str, output: CommandOutput) {
|
|
self.responses
|
|
.lock()
|
|
.unwrap()
|
|
.insert(program.to_string(), output);
|
|
}
|
|
|
|
pub fn set_default(&self, output: CommandOutput) {
|
|
*self.default.lock().unwrap() = Some(output);
|
|
}
|
|
|
|
pub fn fail(&self, program: &str, stderr: &str) {
|
|
self.set_response(
|
|
program,
|
|
CommandOutput {
|
|
status: 1,
|
|
success: false,
|
|
stdout: Vec::new(),
|
|
stderr: stderr.as_bytes().to_vec(),
|
|
duration: Duration::from_millis(1),
|
|
},
|
|
);
|
|
}
|
|
|
|
pub fn recorded(&self) -> Vec<CommandSpec> {
|
|
self.recorded.lock().unwrap().clone()
|
|
}
|
|
|
|
pub fn programs(&self) -> Vec<String> {
|
|
self.recorded().iter().map(|s| s.program.clone()).collect()
|
|
}
|
|
|
|
pub fn len(&self) -> usize {
|
|
self.recorded.lock().unwrap().len()
|
|
}
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
self.len() == 0
|
|
}
|
|
}
|
|
|
|
impl ProcessRunner for RecordingRunner {
|
|
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
|
|
self.recorded.lock().unwrap().push(spec.clone());
|
|
if let Some(out) = self.responses.lock().unwrap().get(&spec.program) {
|
|
return Ok(out.clone());
|
|
}
|
|
if let Some(out) = self.default.lock().unwrap().clone() {
|
|
return Ok(out);
|
|
}
|
|
Ok(CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: Vec::new(),
|
|
stderr: Vec::new(),
|
|
duration: Duration::from_millis(1),
|
|
})
|
|
}
|
|
}
|
|
|
|
/// A runner that refuses to execute and returns a failure for every command.
|
|
/// Useful for proving that dry-run never reaches the system.
|
|
pub struct NeverRunner;
|
|
|
|
impl ProcessRunner for NeverRunner {
|
|
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
|
|
Err(ExecError::operation(
|
|
&spec.stage,
|
|
&spec.operation,
|
|
"command attempted while execution is disabled",
|
|
))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn arguments_stay_separate() {
|
|
let spec = CommandSpec::new("s", "op", "mkfs.btrfs")
|
|
.arg("-f")
|
|
.arg("/dev/vda2")
|
|
.arg("-L")
|
|
.arg("phoebus");
|
|
assert_eq!(spec.args, vec!["-f", "/dev/vda2", "-L", "phoebus"]);
|
|
assert_eq!(spec.program, "mkfs.btrfs");
|
|
}
|
|
|
|
#[test]
|
|
fn recording_runner_records_and_responds() {
|
|
let runner = RecordingRunner::new();
|
|
runner.fail("sgdisk", "boom");
|
|
let spec = CommandSpec::new("storage", "partition", "sgdisk").arg("--zap-all");
|
|
let out = runner.execute(&spec).unwrap();
|
|
assert!(!out.success);
|
|
assert_eq!(runner.programs(), vec!["sgdisk"]);
|
|
}
|
|
|
|
#[test]
|
|
fn real_runner_runs_a_trivial_command() {
|
|
let runner = RealRunner::new();
|
|
let spec = CommandSpec::new("test", "true", "true");
|
|
assert!(runner.execute(&spec).unwrap().success);
|
|
}
|
|
}
|