exec: move line capture out of context
The line sink, stream and pump are not context concerns: the host runner and every sandbox backend feed the same cleaned lines to the terminal. Move them and the fd sanitizer to exec, and have LocalDriver delegate to the shared host runner. Add a run_captured test against sh to pin the two-stream contract before the sandbox backends move.
This commit is contained in:
1 parent
bf88ce4f4d
commit
48306f3719
18 files changed
+326
-271
No files matched your search
+2
-2
@@ -18,11 +18,11 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::context::capture::pump;
|
|
||||||
use crate::context::{LineSink, Stream};
|
|
||||||
use crate::debian::{
|
use crate::debian::{
|
||||||
ChecksumEntry, ControlInfo, FileChecksums, FilesEntry, FilesList, parse_paragraphs,
|
ChecksumEntry, ControlInfo, FileChecksums, FilesEntry, FilesList, parse_paragraphs,
|
||||||
};
|
};
|
||||||
|
use crate::exec::pump;
|
||||||
|
use crate::exec::{LineSink, Stream};
|
||||||
use crate::logfmt::{DpkgSourceClassifier, GenericClassifier};
|
use crate::logfmt::{DpkgSourceClassifier, GenericClassifier};
|
||||||
use crate::report::{BuildTarget, BuildView, Prompter};
|
use crate::report::{BuildTarget, BuildView, Prompter};
|
||||||
|
|
||||||
|
|||||||
+1
-18
@@ -5,24 +5,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
|
|
||||||
/// Stream from which a captured output line originates
|
use crate::exec::LineSink;
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum Stream {
|
|
||||||
/// Standard output of the subprocess
|
|
||||||
Stdout,
|
|
||||||
/// Standard error of the subprocess
|
|
||||||
Stderr,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Receiver for lines captured from a subprocess
|
|
||||||
///
|
|
||||||
/// Implementations receive every decoded line (ANSI escapes stripped,
|
|
||||||
/// carriage-return progress fragments collapsed) as soon as it is produced,
|
|
||||||
/// allowing live UIs to display and rewrite subprocess output while it runs.
|
|
||||||
pub trait LineSink: Send + Sync {
|
|
||||||
/// Called for each captured line
|
|
||||||
fn line(&self, stream: Stream, line: &str);
|
|
||||||
}
|
|
||||||
|
|
||||||
use super::local::LocalDriver;
|
use super::local::LocalDriver;
|
||||||
use super::schroot::SchrootDriver;
|
use super::schroot::SchrootDriver;
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
//! Shared helpers for capturing subprocess output line by line
|
|
||||||
//!
|
|
||||||
//! Used by the context drivers implementing
|
|
||||||
//! [`ContextDriver::run_captured`](super::api::ContextDriver::run_captured):
|
|
||||||
//! raw bytes are read incrementally, split into lines, cleaned up (ANSI escape
|
|
||||||
//! stripping, carriage-return progress collapsing) and forwarded to a
|
|
||||||
//! [`LineSink`](super::api::LineSink).
|
|
||||||
|
|
||||||
use std::io::Read;
|
|
||||||
use std::sync::OnceLock;
|
|
||||||
|
|
||||||
use super::api::{LineSink, Stream};
|
|
||||||
use regex::Regex;
|
|
||||||
|
|
||||||
/// Precompiled regex matching ANSI escape sequences (CSI and simple escapes)
|
|
||||||
fn ansi_regex() -> &'static Regex {
|
|
||||||
static RE: OnceLock<Regex> = OnceLock::new();
|
|
||||||
RE.get_or_init(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])").unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Strip ANSI escape sequences from a line
|
|
||||||
pub(crate) fn strip_ansi(line: &str) -> String {
|
|
||||||
ansi_regex().replace_all(line, "").to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Read `reader` to EOF, forwarding each decoded line to `sink`
|
|
||||||
///
|
|
||||||
/// Lines are split on `\n`; when a line contains carriage returns (e.g. apt's
|
|
||||||
/// `0% [Working]` progress fragments), only the last `\r`-segment is kept so
|
|
||||||
/// progress updates replace each other instead of accumulating. Empty lines
|
|
||||||
/// are dropped.
|
|
||||||
pub(crate) fn pump<R: Read>(mut reader: R, stream: Stream, sink: &dyn LineSink) {
|
|
||||||
let mut buf: Vec<u8> = Vec::with_capacity(8192);
|
|
||||||
let mut chunk = [0u8; 4096];
|
|
||||||
|
|
||||||
loop {
|
|
||||||
match reader.read(&mut chunk) {
|
|
||||||
Ok(0) => break,
|
|
||||||
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
|
||||||
Err(_) => break,
|
|
||||||
}
|
|
||||||
|
|
||||||
while let Some(pos) = buf.iter().position(|&b| b == b'\n') {
|
|
||||||
let line: Vec<u8> = buf.drain(..=pos).collect();
|
|
||||||
emit(&line[..line.len() - 1], stream, sink);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flush a trailing line without newline, if any
|
|
||||||
if !buf.is_empty() {
|
|
||||||
emit(&buf, stream, sink);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Clean up and forward one raw line to the sink
|
|
||||||
fn emit(raw: &[u8], stream: Stream, sink: &dyn LineSink) {
|
|
||||||
let mut line = String::from_utf8_lossy(raw).to_string();
|
|
||||||
|
|
||||||
// Strip a trailing carriage return left over from CRLF line endings
|
|
||||||
if line.ends_with('\r') {
|
|
||||||
line.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Carriage-return progress: keep only the last segment of the line
|
|
||||||
if let Some(idx) = line.rfind('\r') {
|
|
||||||
line = line[idx + 1..].to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
let line = strip_ansi(&line);
|
|
||||||
let trimmed = line.trim_end();
|
|
||||||
if trimmed.trim().is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
sink.line(stream, trimmed);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct CollectingSink(Mutex<Vec<(Stream, String)>>);
|
|
||||||
|
|
||||||
impl LineSink for CollectingSink {
|
|
||||||
fn line(&self, stream: Stream, line: &str) {
|
|
||||||
self.0.lock().unwrap().push((stream, line.to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_pump_splits_lines_and_merges_cr_fragments() {
|
|
||||||
let sink = CollectingSink::default();
|
|
||||||
let data =
|
|
||||||
b"Get:1 http://x InRelease [1 kB]\r0% [Working]\r\nHit:2 http://y Release\npartial";
|
|
||||||
pump(&data[..], Stream::Stdout, &sink);
|
|
||||||
|
|
||||||
let lines = sink.0.lock().unwrap().clone();
|
|
||||||
assert_eq!(
|
|
||||||
lines,
|
|
||||||
vec![
|
|
||||||
(Stream::Stdout, "0% [Working]".to_string()),
|
|
||||||
(Stream::Stdout, "Hit:2 http://y Release".to_string()),
|
|
||||||
(Stream::Stdout, "partial".to_string()),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_pump_strips_ansi_and_skips_empty_lines() {
|
|
||||||
let sink = CollectingSink::default();
|
|
||||||
let data = b"\x1b[1mSetting up foo\x1b[0m\n\n \nE: boom\n";
|
|
||||||
pump(&data[..], Stream::Stderr, &sink);
|
|
||||||
|
|
||||||
let lines = sink.0.lock().unwrap().clone();
|
|
||||||
assert_eq!(
|
|
||||||
lines,
|
|
||||||
vec![
|
|
||||||
(Stream::Stderr, "Setting up foo".to_string()),
|
|
||||||
(Stream::Stderr, "E: boom".to_string()),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+5
-108
@@ -1,41 +1,15 @@
|
|||||||
/// Local context: execute commands locally
|
/// Local context: execute commands locally
|
||||||
/// Context driver: Does nothing
|
/// Context driver: Does nothing
|
||||||
use super::api::{ContextDriver, LineSink, Stream};
|
use super::api::ContextDriver;
|
||||||
use super::capture::pump;
|
use crate::exec::{self, LineSink};
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::os::unix::fs::symlink;
|
use std::os::unix::fs::symlink;
|
||||||
use std::os::unix::process::CommandExt;
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
|
||||||
pub struct LocalDriver;
|
pub struct LocalDriver;
|
||||||
|
|
||||||
/// Close every file descriptor above stdio in the spawned child
|
|
||||||
///
|
|
||||||
/// pkh's process legitimately carries descriptors that stay open for its
|
|
||||||
/// lifetime (the async runtime, gpgme sockets, the log tee), and std passes
|
|
||||||
/// any inheritable one to children. Tools with fd-number assumptions then
|
|
||||||
/// see their low-numbered allocations land on two-digit fds: mmdebstrap's
|
|
||||||
/// apt hook is `cat >&N`, which /bin/sh (dash) rejects for N >= 10 with
|
|
||||||
/// "Bad fd number" — the fresh-chroot bootstrap died exactly there. A
|
|
||||||
/// clean child table keeps those numbers single-digit.
|
|
||||||
fn sanitize_fds(cmd: &mut Command) {
|
|
||||||
unsafe {
|
|
||||||
cmd.pre_exec(|| {
|
|
||||||
// One syscall when the kernel has close_range; the loop
|
|
||||||
// covers the rest (and is what the syscall does anyway).
|
|
||||||
if libc::syscall(libc::SYS_close_range, 3, libc::c_uint::MAX, 0u32) != 0 {
|
|
||||||
for fd in 3..1024 {
|
|
||||||
libc::close(fd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ContextDriver for LocalDriver {
|
impl ContextDriver for LocalDriver {
|
||||||
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
||||||
let dest_root_path = Path::new(dest_root);
|
let dest_root_path = Path::new(dest_root);
|
||||||
@@ -97,13 +71,7 @@ impl ContextDriver for LocalDriver {
|
|||||||
env: &[(String, String)],
|
env: &[(String, String)],
|
||||||
cwd: Option<&str>,
|
cwd: Option<&str>,
|
||||||
) -> io::Result<std::process::ExitStatus> {
|
) -> io::Result<std::process::ExitStatus> {
|
||||||
let mut cmd = Command::new(program);
|
exec::run(program, args, env, cwd)
|
||||||
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
|
||||||
if let Some(dir) = cwd {
|
|
||||||
cmd.current_dir(dir);
|
|
||||||
}
|
|
||||||
sanitize_fds(&mut cmd);
|
|
||||||
cmd.status()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_captured(
|
fn run_captured(
|
||||||
@@ -114,42 +82,7 @@ impl ContextDriver for LocalDriver {
|
|||||||
cwd: Option<&str>,
|
cwd: Option<&str>,
|
||||||
sink: Arc<dyn LineSink>,
|
sink: Arc<dyn LineSink>,
|
||||||
) -> io::Result<std::process::ExitStatus> {
|
) -> io::Result<std::process::ExitStatus> {
|
||||||
let mut cmd = Command::new(program);
|
exec::run_captured(program, args, env, cwd, sink)
|
||||||
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
|
||||||
// Best-effort: ask children not to emit ANSI colors; captured lines are
|
|
||||||
// stripped anyway.
|
|
||||||
cmd.env("NO_COLOR", "1");
|
|
||||||
if let Some(dir) = cwd {
|
|
||||||
cmd.current_dir(dir);
|
|
||||||
}
|
|
||||||
cmd.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::piped())
|
|
||||||
.stdin(Stdio::null());
|
|
||||||
sanitize_fds(&mut cmd);
|
|
||||||
|
|
||||||
let mut child = cmd.spawn()?;
|
|
||||||
let stdout = child.stdout.take();
|
|
||||||
let stderr = child.stderr.take();
|
|
||||||
|
|
||||||
// One reader thread per stream; lines are forwarded to the sink as
|
|
||||||
// they arrive so the UI stays live.
|
|
||||||
let out_sink = sink.clone();
|
|
||||||
let t_out =
|
|
||||||
stdout.map(|r| std::thread::spawn(move || pump(r, Stream::Stdout, out_sink.as_ref())));
|
|
||||||
let err_sink = sink.clone();
|
|
||||||
let t_err =
|
|
||||||
stderr.map(|r| std::thread::spawn(move || pump(r, Stream::Stderr, err_sink.as_ref())));
|
|
||||||
|
|
||||||
let status = child.wait();
|
|
||||||
|
|
||||||
if let Some(t) = t_out {
|
|
||||||
let _ = t.join();
|
|
||||||
}
|
|
||||||
if let Some(t) = t_err {
|
|
||||||
let _ = t.join();
|
|
||||||
}
|
|
||||||
|
|
||||||
status
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_output(
|
fn run_output(
|
||||||
@@ -159,13 +92,7 @@ impl ContextDriver for LocalDriver {
|
|||||||
env: &[(String, String)],
|
env: &[(String, String)],
|
||||||
cwd: Option<&str>,
|
cwd: Option<&str>,
|
||||||
) -> io::Result<std::process::Output> {
|
) -> io::Result<std::process::Output> {
|
||||||
let mut cmd = Command::new(program);
|
exec::run_output(program, args, env, cwd)
|
||||||
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
|
||||||
if let Some(dir) = cwd {
|
|
||||||
cmd.current_dir(dir);
|
|
||||||
}
|
|
||||||
sanitize_fds(&mut cmd);
|
|
||||||
cmd.output()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||||
@@ -255,34 +182,4 @@ mod tests {
|
|||||||
std::fs::remove_dir(name).unwrap();
|
std::fs::remove_dir(name).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inherited descriptors must not leak into spawned children: the
|
|
||||||
/// tools' low-numbered fd assumptions break on a shifted table
|
|
||||||
/// (mmdebstrap's dash-executed `cat >&N` apt hook).
|
|
||||||
#[test]
|
|
||||||
fn spawned_children_get_a_clean_fd_table() {
|
|
||||||
// Raw open(): std marks its own descriptors close-on-exec, which
|
|
||||||
// would make the test pass vacuously.
|
|
||||||
let mut strays = Vec::new();
|
|
||||||
for _ in 0..8 {
|
|
||||||
let path = std::ffi::CString::new("/dev/null").unwrap();
|
|
||||||
let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR) };
|
|
||||||
assert!(fd >= 0);
|
|
||||||
strays.push(fd);
|
|
||||||
}
|
|
||||||
let mut cmd = Command::new("sh");
|
|
||||||
cmd.arg("-c").arg("ls /proc/self/fd");
|
|
||||||
sanitize_fds(&mut cmd);
|
|
||||||
let out = cmd.output().unwrap();
|
|
||||||
for fd in strays {
|
|
||||||
unsafe { libc::close(fd) };
|
|
||||||
}
|
|
||||||
|
|
||||||
// stdio (3) + the directory ls itself opened (1)
|
|
||||||
let table = String::from_utf8_lossy(&out.stdout);
|
|
||||||
assert!(
|
|
||||||
table.lines().count() <= 5,
|
|
||||||
"child fd table should be clean, got:\n{table}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,5 +1,4 @@
|
|||||||
mod api;
|
mod api;
|
||||||
pub(crate) mod capture;
|
|
||||||
mod local;
|
mod local;
|
||||||
mod manager;
|
mod manager;
|
||||||
mod schroot;
|
mod schroot;
|
||||||
@@ -7,7 +6,8 @@ pub(crate) mod shell;
|
|||||||
mod ssh;
|
mod ssh;
|
||||||
mod unshare;
|
mod unshare;
|
||||||
|
|
||||||
pub use api::{Context, ContextCommand, ContextConfig, LineSink, OverlayStaging, Stream};
|
pub use crate::exec::{LineSink, Stream};
|
||||||
|
pub use api::{Context, ContextCommand, ContextConfig, OverlayStaging};
|
||||||
pub(crate) use api::{MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV};
|
pub(crate) use api::{MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV};
|
||||||
// The driver trait is implementation detail of the context API; it is only
|
// The driver trait is implementation detail of the context API; it is only
|
||||||
// needed crate-internally (test-run capture wrapper), so keep it out of the
|
// needed crate-internally (test-run capture wrapper), so keep it out of the
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
/// Schroot context: execute commands in a schroot session
|
/// Schroot context: execute commands in a schroot session
|
||||||
/// Not tested, will need more work!
|
/// Not tested, will need more work!
|
||||||
use super::api::{Context, ContextConfig, ContextDriver, LineSink};
|
use super::api::{Context, ContextConfig, ContextDriver};
|
||||||
use super::shell::shell_quote;
|
use super::shell::shell_quote;
|
||||||
|
use crate::exec::LineSink;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
/// SSH context: execute commands over an SSH connection
|
/// SSH context: execute commands over an SSH connection
|
||||||
/// Context driver: Copies over SFTP with ssh2, executes commands over ssh2 channels
|
/// Context driver: Copies over SFTP with ssh2, executes commands over ssh2 channels
|
||||||
use super::api::{ContextDriver, LineSink, Stream};
|
use super::api::ContextDriver;
|
||||||
use super::capture::pump;
|
|
||||||
use super::shell::shell_quote;
|
use super::shell::shell_quote;
|
||||||
|
use crate::exec::{LineSink, Stream, pump};
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use ssh2;
|
use ssh2;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use super::api::{
|
use super::api::{Context, ContextCommand, ContextDriver, MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV};
|
||||||
Context, ContextCommand, ContextDriver, LineSink, MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV,
|
|
||||||
};
|
|
||||||
use super::shell::shell_quote;
|
use super::shell::shell_quote;
|
||||||
|
use crate::exec::LineSink;
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|||||||
+2
-1
@@ -1,7 +1,8 @@
|
|||||||
/// Local binary package building
|
/// Local binary package building
|
||||||
/// Directly calling 'debian/rules' in current context
|
/// Directly calling 'debian/rules' in current context
|
||||||
use crate::context::{Context, ContextCommand, LineSink};
|
use crate::context::{Context, ContextCommand};
|
||||||
use crate::deb::{BuildProfiler, Phase, enter_phase, find_dsc_file};
|
use crate::deb::{BuildProfiler, Phase, enter_phase, find_dsc_file};
|
||||||
|
use crate::exec::LineSink;
|
||||||
use crate::logfmt::QuiltClassifier;
|
use crate::logfmt::QuiltClassifier;
|
||||||
use crate::report::BuildView;
|
use crate::report::BuildView;
|
||||||
use log::warn;
|
use log::warn;
|
||||||
|
|||||||
+2
-2
@@ -302,7 +302,7 @@ impl BuildView for RecordLogView<'_> {
|
|||||||
self.inner.byte_progress(label, pos, total);
|
self.inner.byte_progress(label, pos, total);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sink(&self) -> Option<Arc<dyn crate::context::LineSink>> {
|
fn sink(&self) -> Option<Arc<dyn crate::exec::LineSink>> {
|
||||||
Some(self.log.clone())
|
Some(self.log.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2119,8 +2119,8 @@ mod tests {
|
|||||||
/// build.log and on the writers (the terminal, in production).
|
/// build.log and on the writers (the terminal, in production).
|
||||||
#[test]
|
#[test]
|
||||||
fn record_log_view_shows_raw_output_when_the_view_has_no_sink() {
|
fn record_log_view_shows_raw_output_when_the_view_has_no_sink() {
|
||||||
use crate::context::{LineSink, Stream};
|
|
||||||
use crate::deb::session::record_fixtures::SharedWriter;
|
use crate::deb::session::record_fixtures::SharedWriter;
|
||||||
|
use crate::exec::{LineSink, Stream};
|
||||||
|
|
||||||
let (root, _tarball) = sessions_fixture();
|
let (root, _tarball) = sessions_fixture();
|
||||||
let identity = test_identity();
|
let identity = test_identity();
|
||||||
|
|||||||
+1
-1
@@ -54,7 +54,7 @@ use std::time::Duration;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::context::{LineSink, Stream};
|
use crate::exec::{LineSink, Stream};
|
||||||
|
|
||||||
/// Manifest schema version: a record recorded by another schema is
|
/// Manifest schema version: a record recorded by another schema is
|
||||||
/// ignored (and eventually pruned) rather than forked.
|
/// ignored (and eventually pruned) rather than forked.
|
||||||
|
|||||||
+295
@@ -0,0 +1,295 @@
|
|||||||
|
//! Subprocess execution and line capture.
|
||||||
|
//!
|
||||||
|
//! The host runner and every sandbox backend feed captured output through
|
||||||
|
//! [`pump`], so the terminal sees the same cleaned lines whatever runs the
|
||||||
|
//! command.
|
||||||
|
|
||||||
|
use std::io::{self, Read};
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
use std::process::{Command, ExitStatus, Output, Stdio};
|
||||||
|
use std::sync::{Arc, OnceLock};
|
||||||
|
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
/// Stream from which a captured output line originates
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Stream {
|
||||||
|
/// Standard output of the subprocess
|
||||||
|
Stdout,
|
||||||
|
/// Standard error of the subprocess
|
||||||
|
Stderr,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Receiver for lines captured from a subprocess
|
||||||
|
///
|
||||||
|
/// Implementations receive every decoded line (ANSI escapes stripped,
|
||||||
|
/// carriage-return progress fragments collapsed) as soon as it is produced,
|
||||||
|
/// allowing live UIs to display and rewrite subprocess output while it runs.
|
||||||
|
pub trait LineSink: Send + Sync {
|
||||||
|
/// Called for each captured line
|
||||||
|
fn line(&self, stream: Stream, line: &str);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Precompiled regex matching ANSI escape sequences (CSI and simple escapes)
|
||||||
|
fn ansi_regex() -> &'static Regex {
|
||||||
|
static RE: OnceLock<Regex> = OnceLock::new();
|
||||||
|
RE.get_or_init(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])").unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strip ANSI escape sequences from a line
|
||||||
|
pub(crate) fn strip_ansi(line: &str) -> String {
|
||||||
|
ansi_regex().replace_all(line, "").to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read `reader` to EOF, forwarding each decoded line to `sink`
|
||||||
|
///
|
||||||
|
/// Lines are split on `\n`; when a line contains carriage returns (e.g. apt's
|
||||||
|
/// `0% [Working]` progress fragments), only the last `\r`-segment is kept so
|
||||||
|
/// progress updates replace each other instead of accumulating. Empty lines
|
||||||
|
/// are dropped.
|
||||||
|
pub(crate) fn pump<R: Read>(mut reader: R, stream: Stream, sink: &dyn LineSink) {
|
||||||
|
let mut buf: Vec<u8> = Vec::with_capacity(8192);
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
|
||||||
|
loop {
|
||||||
|
match reader.read(&mut chunk) {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(pos) = buf.iter().position(|&b| b == b'\n') {
|
||||||
|
let line: Vec<u8> = buf.drain(..=pos).collect();
|
||||||
|
emit(&line[..line.len() - 1], stream, sink);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush a trailing line without newline, if any
|
||||||
|
if !buf.is_empty() {
|
||||||
|
emit(&buf, stream, sink);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clean up and forward one raw line to the sink
|
||||||
|
fn emit(raw: &[u8], stream: Stream, sink: &dyn LineSink) {
|
||||||
|
let mut line = String::from_utf8_lossy(raw).to_string();
|
||||||
|
|
||||||
|
// Strip a trailing carriage return left over from CRLF line endings
|
||||||
|
if line.ends_with('\r') {
|
||||||
|
line.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carriage-return progress: keep only the last segment of the line
|
||||||
|
if let Some(idx) = line.rfind('\r') {
|
||||||
|
line = line[idx + 1..].to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
let line = strip_ansi(&line);
|
||||||
|
let trimmed = line.trim_end();
|
||||||
|
if trimmed.trim().is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sink.line(stream, trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close every file descriptor above stdio in the spawned child
|
||||||
|
///
|
||||||
|
/// pkh's process legitimately carries descriptors that stay open for its
|
||||||
|
/// lifetime (the async runtime, gpgme sockets, the log tee), and std passes
|
||||||
|
/// any inheritable one to children. Tools with fd-number assumptions then
|
||||||
|
/// see their low-numbered allocations land on two-digit fds: mmdebstrap's
|
||||||
|
/// apt hook is `cat >&N`, which /bin/sh (dash) rejects for N >= 10 with
|
||||||
|
/// "Bad fd number" — the fresh-chroot bootstrap died exactly there. A
|
||||||
|
/// clean child table keeps those numbers single-digit.
|
||||||
|
pub(crate) fn sanitize_fds(cmd: &mut Command) {
|
||||||
|
unsafe {
|
||||||
|
cmd.pre_exec(|| {
|
||||||
|
// One syscall when the kernel has close_range; the loop
|
||||||
|
// covers the rest (and is what the syscall does anyway).
|
||||||
|
if libc::syscall(libc::SYS_close_range, 3, libc::c_uint::MAX, 0u32) != 0 {
|
||||||
|
for fd in 3..1024 {
|
||||||
|
libc::close(fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a host command with inherited standard streams
|
||||||
|
pub(crate) fn run(
|
||||||
|
program: &str,
|
||||||
|
args: &[String],
|
||||||
|
env: &[(String, String)],
|
||||||
|
cwd: Option<&str>,
|
||||||
|
) -> io::Result<ExitStatus> {
|
||||||
|
let mut cmd = Command::new(program);
|
||||||
|
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
||||||
|
if let Some(dir) = cwd {
|
||||||
|
cmd.current_dir(dir);
|
||||||
|
}
|
||||||
|
sanitize_fds(&mut cmd);
|
||||||
|
cmd.status()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a host command, forwarding its output line by line to `sink`
|
||||||
|
pub(crate) fn run_captured(
|
||||||
|
program: &str,
|
||||||
|
args: &[String],
|
||||||
|
env: &[(String, String)],
|
||||||
|
cwd: Option<&str>,
|
||||||
|
sink: Arc<dyn LineSink>,
|
||||||
|
) -> io::Result<ExitStatus> {
|
||||||
|
let mut cmd = Command::new(program);
|
||||||
|
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
||||||
|
// Best-effort: ask children not to emit ANSI colors; captured lines are
|
||||||
|
// stripped anyway.
|
||||||
|
cmd.env("NO_COLOR", "1");
|
||||||
|
if let Some(dir) = cwd {
|
||||||
|
cmd.current_dir(dir);
|
||||||
|
}
|
||||||
|
cmd.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.stdin(Stdio::null());
|
||||||
|
sanitize_fds(&mut cmd);
|
||||||
|
|
||||||
|
let mut child = cmd.spawn()?;
|
||||||
|
let stdout = child.stdout.take();
|
||||||
|
let stderr = child.stderr.take();
|
||||||
|
|
||||||
|
// One reader thread per stream; lines are forwarded to the sink as
|
||||||
|
// they arrive so the UI stays live.
|
||||||
|
let out_sink = sink.clone();
|
||||||
|
let t_out =
|
||||||
|
stdout.map(|r| std::thread::spawn(move || pump(r, Stream::Stdout, out_sink.as_ref())));
|
||||||
|
let err_sink = sink.clone();
|
||||||
|
let t_err =
|
||||||
|
stderr.map(|r| std::thread::spawn(move || pump(r, Stream::Stderr, err_sink.as_ref())));
|
||||||
|
|
||||||
|
let status = child.wait();
|
||||||
|
|
||||||
|
if let Some(t) = t_out {
|
||||||
|
let _ = t.join();
|
||||||
|
}
|
||||||
|
if let Some(t) = t_err {
|
||||||
|
let _ = t.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
status
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a host command and capture its complete output
|
||||||
|
pub(crate) fn run_output(
|
||||||
|
program: &str,
|
||||||
|
args: &[String],
|
||||||
|
env: &[(String, String)],
|
||||||
|
cwd: Option<&str>,
|
||||||
|
) -> io::Result<Output> {
|
||||||
|
let mut cmd = Command::new(program);
|
||||||
|
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
||||||
|
if let Some(dir) = cwd {
|
||||||
|
cmd.current_dir(dir);
|
||||||
|
}
|
||||||
|
sanitize_fds(&mut cmd);
|
||||||
|
cmd.output()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct CollectingSink(Mutex<Vec<(Stream, String)>>);
|
||||||
|
|
||||||
|
impl LineSink for CollectingSink {
|
||||||
|
fn line(&self, stream: Stream, line: &str) {
|
||||||
|
self.0.lock().unwrap().push((stream, line.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_pump_splits_lines_and_merges_cr_fragments() {
|
||||||
|
let sink = CollectingSink::default();
|
||||||
|
let data =
|
||||||
|
b"Get:1 http://x InRelease [1 kB]\r0% [Working]\r\nHit:2 http://y Release\npartial";
|
||||||
|
pump(&data[..], Stream::Stdout, &sink);
|
||||||
|
|
||||||
|
let lines = sink.0.lock().unwrap().clone();
|
||||||
|
assert_eq!(
|
||||||
|
lines,
|
||||||
|
vec![
|
||||||
|
(Stream::Stdout, "0% [Working]".to_string()),
|
||||||
|
(Stream::Stdout, "Hit:2 http://y Release".to_string()),
|
||||||
|
(Stream::Stdout, "partial".to_string()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_pump_strips_ansi_and_skips_empty_lines() {
|
||||||
|
let sink = CollectingSink::default();
|
||||||
|
let data = b"\x1b[1mSetting up foo\x1b[0m\n\n \nE: boom\n";
|
||||||
|
pump(&data[..], Stream::Stderr, &sink);
|
||||||
|
|
||||||
|
let lines = sink.0.lock().unwrap().clone();
|
||||||
|
assert_eq!(
|
||||||
|
lines,
|
||||||
|
vec![
|
||||||
|
(Stream::Stderr, "Setting up foo".to_string()),
|
||||||
|
(Stream::Stderr, "E: boom".to_string()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host runner forwards both streams through the same cleaned line
|
||||||
|
/// contract the sandbox backends use.
|
||||||
|
#[test]
|
||||||
|
fn test_run_captured_forwards_stdout_and_stderr() {
|
||||||
|
let sink = Arc::new(CollectingSink::default());
|
||||||
|
let args = vec!["-c".to_string(), "echo out; echo err >&2".to_string()];
|
||||||
|
let status = run_captured("sh", &args, &[], None, sink.clone()).unwrap();
|
||||||
|
assert!(status.success());
|
||||||
|
|
||||||
|
let mut lines = sink.0.lock().unwrap().clone();
|
||||||
|
lines.sort_by(|a, b| a.1.cmp(&b.1));
|
||||||
|
assert_eq!(
|
||||||
|
lines,
|
||||||
|
vec![
|
||||||
|
(Stream::Stderr, "err".to_string()),
|
||||||
|
(Stream::Stdout, "out".to_string()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inherited descriptors must not leak into spawned children: the
|
||||||
|
/// tools' low-numbered fd assumptions break on a shifted table
|
||||||
|
/// (mmdebstrap's dash-executed `cat >&N` apt hook).
|
||||||
|
#[test]
|
||||||
|
fn spawned_children_get_a_clean_fd_table() {
|
||||||
|
// Raw open(): std marks its own descriptors close-on-exec, which
|
||||||
|
// would make the test pass vacuously.
|
||||||
|
let mut strays = Vec::new();
|
||||||
|
for _ in 0..8 {
|
||||||
|
let path = std::ffi::CString::new("/dev/null").unwrap();
|
||||||
|
let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR) };
|
||||||
|
assert!(fd >= 0);
|
||||||
|
strays.push(fd);
|
||||||
|
}
|
||||||
|
let mut cmd = Command::new("sh");
|
||||||
|
cmd.arg("-c").arg("ls /proc/self/fd");
|
||||||
|
sanitize_fds(&mut cmd);
|
||||||
|
let out = cmd.output().unwrap();
|
||||||
|
for fd in strays {
|
||||||
|
unsafe { libc::close(fd) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// stdio (3) + the directory ls itself opened (1)
|
||||||
|
let table = String::from_utf8_lossy(&out.stdout);
|
||||||
|
assert!(
|
||||||
|
table.lines().count() <= 5,
|
||||||
|
"child fd table should be clean, got:\n{table}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,6 +22,9 @@ pub mod deb;
|
|||||||
pub mod debian;
|
pub mod debian;
|
||||||
/// Obtain general information about distribution, series, etc
|
/// Obtain general information about distribution, series, etc
|
||||||
pub mod distro_info;
|
pub mod distro_info;
|
||||||
|
/// Subprocess output capture: stream identification, line sinks, the line
|
||||||
|
/// pump and host process helpers
|
||||||
|
pub mod exec;
|
||||||
/// Passive interrupt state: the interrupted flag, the cleanup hook registry
|
/// Passive interrupt state: the interrupted flag, the cleanup hook registry
|
||||||
/// and the live view's reporter slot (the CLI owns the signal handling)
|
/// and the live view's reporter slot (the CLI owns the signal handling)
|
||||||
pub mod interrupt;
|
pub mod interrupt;
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
use std::sync::{LazyLock, OnceLock};
|
use std::sync::{LazyLock, OnceLock};
|
||||||
|
|
||||||
use crate::context::Stream;
|
use crate::exec::Stream;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
|
||||||
/// Maximum length of a rewritten line displayed in the rolling pane
|
/// Maximum length of a rewritten line displayed in the rolling pane
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ use std::error::Error;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::context::LineSink;
|
use crate::exec::LineSink;
|
||||||
use crate::logfmt::Classifier;
|
use crate::logfmt::Classifier;
|
||||||
|
|
||||||
/// Answer validator of [`Prompter::text`]: accepts the answer, or explains
|
/// Answer validator of [`Prompter::text`]: accepts the answer, or explains
|
||||||
|
|||||||
+1
-1
@@ -27,9 +27,9 @@ use std::fs;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::context::{LineSink, Stream};
|
|
||||||
use crate::debian::control::{ControlInfo, parse_paragraphs};
|
use crate::debian::control::{ControlInfo, parse_paragraphs};
|
||||||
use crate::debian::tests_control::TestsControl;
|
use crate::debian::tests_control::TestsControl;
|
||||||
|
use crate::exec::{LineSink, Stream};
|
||||||
use crate::logfmt::GenericClassifier;
|
use crate::logfmt::GenericClassifier;
|
||||||
use crate::report::{BuildTarget, BuildView, TargetKind};
|
use crate::report::{BuildTarget, BuildView, TargetKind};
|
||||||
use crate::test::bed::Bed;
|
use crate::test::bed::Bed;
|
||||||
|
|||||||
+3
-2
@@ -40,7 +40,7 @@ mod imp {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn subprocess_sink() -> Option<std::sync::Arc<dyn crate::context::LineSink>> {
|
pub(crate) fn subprocess_sink() -> Option<std::sync::Arc<dyn crate::exec::LineSink>> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,7 +78,8 @@ mod imp {
|
|||||||
use std::process::{Command, ExitStatus};
|
use std::process::{Command, ExitStatus};
|
||||||
use std::sync::{Arc, Mutex, OnceLock};
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
|
||||||
use crate::context::{ContextDriver, LineSink, Stream};
|
use crate::context::ContextDriver;
|
||||||
|
use crate::exec::{LineSink, Stream};
|
||||||
|
|
||||||
/// Directory receiving one log file per test
|
/// Directory receiving one log file per test
|
||||||
fn log_dir() -> PathBuf {
|
fn log_dir() -> PathBuf {
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ use directories::ProjectDirs;
|
|||||||
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle};
|
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle};
|
||||||
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
|
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
|
||||||
|
|
||||||
use crate::context::{LineSink, Stream};
|
use crate::exec::{LineSink, Stream};
|
||||||
use crate::logfmt::{Action, Classifier, GenericClassifier};
|
use crate::logfmt::{Action, Classifier, GenericClassifier};
|
||||||
use crate::report::BuildTarget;
|
use crate::report::BuildTarget;
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user