Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't read stderr into memory when not captured #148

Merged
merged 8 commits into from
Aug 10, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ keywords = ["child", "child-process", "command", "process", "shell"]
categories = ["filesystem", "os"]

[workspace]
members = [".", "memory-test"]
members = [".", "memory-tests"]

[dependencies]
rustversion = "1.0.4"
Expand Down
8 changes: 0 additions & 8 deletions memory-test/src/bin/cradle_user.rs

This file was deleted.

17 changes: 0 additions & 17 deletions memory-test/src/bin/produce_bytes.rs

This file was deleted.

2 changes: 1 addition & 1 deletion memory-test/Cargo.toml → memory-tests/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "memory-test"
name = "memory-tests"
version = "0.0.0"
edition = "2018"

Expand Down
13 changes: 13 additions & 0 deletions memory-tests/src/bin/cradle_user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use cradle::prelude::*;

fn main() {
let mut args = std::env::args();
let stream_type: String = args.nth(1).unwrap();
let bytes: usize = args.next().unwrap().parse().unwrap();
eprintln!("consuming {} KiB", bytes / 2_usize.pow(10));
cmd_unit!(
"./target/release/produce_bytes",
stream_type,
bytes.to_string()
);
}
22 changes: 22 additions & 0 deletions memory-tests/src/bin/produce_bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use anyhow::Result;
use std::io::{self, Write};

fn main() -> Result<()> {
let mut args = std::env::args();
let stream_type: String = args.nth(1).unwrap();
let mut bytes: usize = args.next().unwrap().parse()?;
eprintln!("writing {} KiB to {}", bytes / 2_usize.pow(10), stream_type);
let buffer = &[b'x'; 1024];
let mut stream: Box<dyn Write> = match stream_type.as_str() {
"stdout" => Box::new(io::stdout()),
"stderr" => Box::new(io::stderr()),
_ => panic!("unknown stream type: {}", stream_type),
};
while bytes > 0 {
let chunk_size = bytes.min(1024);
stream.write_all(&buffer[..chunk_size])?;
bytes -= chunk_size;
soenkehahn marked this conversation as resolved.
Show resolved Hide resolved
}
stream.flush()?;
Ok(())
}
18 changes: 12 additions & 6 deletions memory-test/src/bin/run_test.rs → memory-tests/src/bin/run.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@
use anyhow::Result;
use cradle::prelude::*;
use std::process::{Command, Stdio};

fn from_mib(mebibytes: usize) -> usize {
mebibytes * 2_usize.pow(20)
}

fn main() -> Result<()> {
Split("cargo build --release").run_unit();
test("stdout")?;
test("stderr")?;
Ok(())
}

fn test(stream_type: &str) -> Result<()> {
let bytes = from_mib(64);
let memory_consumption = measure_memory_consumption(bytes)?;
let memory_consumption = measure_memory_consumption(stream_type, bytes)?;
let allowed_memory_consumption = from_mib(16);
assert!(
memory_consumption < allowed_memory_consumption,
"Maximum resident set size: {}, allowed upper limit: {}",
"stream type: {}, Maximum resident set size: {}, allowed upper limit: {}",
stream_type,
memory_consumption,
allowed_memory_consumption
);
Ok(())
}

fn measure_memory_consumption(bytes: usize) -> Result<usize> {
fn measure_memory_consumption(stream_type: &str, bytes: usize) -> Result<usize> {
let output = Command::new("/usr/bin/time")
.arg("-v")
.arg("./target/release/cradle_user")
.arg(stream_type)
.arg(bytes.to_string())
.stdout(Stdio::null())
.output()?;
let stderr = String::from_utf8(output.stderr)?;
eprintln!("{}", stderr);
if !output.status.success() {
eprintln!("{}", stderr);
panic!("running 'cradle_user' failed");
}
let memory_size_prefix = "Maximum resident set size (kbytes): ";
Expand Down
16 changes: 11 additions & 5 deletions src/collected_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
pub(crate) struct Waiter {
stdin: JoinHandle<io::Result<()>>,
stdout: JoinHandle<io::Result<Option<Vec<u8>>>>,
stderr: JoinHandle<io::Result<Vec<u8>>>,
stderr: JoinHandle<io::Result<Option<Vec<u8>>>>,
}

impl Waiter {
Expand Down Expand Up @@ -54,15 +54,21 @@ impl Waiter {
});
let mut context_clone = context.clone();
let capture_stderr = config.capture_stderr;
let stderr_join_handle = thread::spawn(move || -> io::Result<Vec<u8>> {
let mut collected_stderr = Vec::new();
let stderr_join_handle = thread::spawn(move || -> io::Result<Option<Vec<u8>>> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this could be DRYed up. The code here seems nontrivial, so merging the stdout and stderr capture would be nice.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of 4015e1c?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, looks good.

let mut collected_stderr = if capture_stderr {
Some(Vec::new())
} else {
None
};
let buffer = &mut [0; 256];
loop {
let length = child_stderr.read(buffer)?;
if (length) == 0 {
break;
}
collected_stderr.extend(&buffer[..length]);
if let Some(collected_stderr) = &mut collected_stderr {
collected_stderr.extend(&buffer[..length]);
}
if !capture_stderr {
context_clone.stderr.write_all(&buffer[..length])?;
}
Expand Down Expand Up @@ -96,5 +102,5 @@ impl Waiter {
#[derive(Debug)]
pub(crate) struct CollectedOutput {
pub(crate) stdout: Option<Vec<u8>>,
pub(crate) stderr: Vec<u8>,
pub(crate) stderr: Option<Vec<u8>>,
}
4 changes: 3 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub enum Error {
source: Arc<FromUtf8Error>,
},
Internal {
message: String,
full_command: String,
config: Config,
},
Expand All @@ -40,8 +41,9 @@ impl Error {
}
}

pub(crate) fn internal(config: &Config) -> Error {
pub(crate) fn internal(message: &str, config: &Config) -> Error {
Error::Internal {
message: message.to_string(),
full_command: config.full_command(),
config: config.clone(),
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ where
#[derive(Clone, Debug)]
pub struct RunResult {
stdout: Option<Vec<u8>>,
stderr: Vec<u8>,
stderr: Option<Vec<u8>>,
exit_status: ExitStatus,
}

Expand Down
16 changes: 10 additions & 6 deletions src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,9 @@ impl Output for StdoutUntrimmed {

#[doc(hidden)]
fn from_run_result(config: &Config, result: Result<RunResult, Error>) -> Result<Self, Error> {
let result = result?;
let stdout = result.stdout.ok_or_else(|| Error::internal(config))?;
let stdout = result?
.stdout
.ok_or_else(|| Error::internal("stdout not captured", config))?;
Ok(StdoutUntrimmed(String::from_utf8(stdout).map_err(
|source| Error::InvalidUtf8ToStdout {
full_command: config.full_command(),
Expand Down Expand Up @@ -209,12 +210,15 @@ impl Output for Stderr {

#[doc(hidden)]
fn from_run_result(config: &Config, result: Result<RunResult, Error>) -> Result<Self, Error> {
Ok(Stderr(String::from_utf8(result?.stderr).map_err(
|source| Error::InvalidUtf8ToStderr {
let stderr = result?
.stderr
.ok_or_else(|| Error::internal("stderr not captured", config))?;
Ok(Stderr(String::from_utf8(stderr).map_err(|source| {
Error::InvalidUtf8ToStderr {
full_command: config.full_command(),
source: Arc::new(source),
},
)?))
}
})?))
}
}

Expand Down
4 changes: 2 additions & 2 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,6 @@ mod run_interface {
#[test]
fn memory_test() {
use cradle::prelude::*;
cmd_unit!(%"cargo build -p memory-test --release");
cmd_unit!(%"cargo run -p memory-test --bin run_test");
cmd_unit!(%"cargo build -p memory-tests --release");
cmd_unit!(%"cargo run -p memory-tests --bin run");
}