use crate::memory::resident_bytes;
const START_CHUNK_BYTES: usize = 64 * 1024 * 1024;
const MIN_CHUNK_BYTES: usize = 4 * 1024;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum InflateError {
Allocation {
attempted: usize,
},
Join(String),
}
impl std::fmt::Display for InflateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Allocation { attempted } => {
write!(
f,
"failed to allocate even the minimum memory chunk of {attempted} bytes before reaching the limit"
)
}
Self::Join(reason) => {
write!(
f,
"memory inflation background task was terminated: {reason}"
)
}
}
}
}
impl std::error::Error for InflateError {}
pub(crate) async fn inflate(limit: u64) -> Result<(), InflateError> {
let current = resident_bytes();
if let Some(resident) = current
&& resident >= limit
{
tracing::info!(
limit,
resident,
"memory inflation is skipped: the process is already at or above the limit"
);
return Ok(());
}
match current {
Some(resident) => {
tracing::info!(limit, resident, "inflating process memory up to the limit")
}
None => tracing::info!(
limit,
"inflating process memory up to the limit; the current resident usage is unknown"
),
}
let handle = tokio::task::spawn_blocking(move || inflate_blocking(limit, current));
match handle.await {
Ok(result) => result,
Err(error) => Err(InflateError::Join(error.to_string())),
}
}
#[allow(clippy::slow_vector_initialization)]
fn inflate_blocking(limit: u64, initial: Option<u64>) -> Result<(), InflateError> {
let mut chunks: Vec<Vec<u8>> = Vec::new();
let mut chunk_size = START_CHUNK_BYTES;
let mut held_bytes: usize = 0;
let mut usage = initial;
loop {
if let Some(resident) = resident_bytes() {
usage = Some(resident);
if resident >= limit {
tracing::debug!(
limit,
resident,
held = held_bytes,
chunks = chunks.len(),
"memory inflation reached the limit"
);
std::mem::forget(chunks);
return Ok(());
}
}
let remaining = usage.map_or(chunk_size, |resident| {
usize::try_from(limit - resident).unwrap_or(chunk_size)
});
let size = chunk_size.min(remaining);
chunks
.try_reserve_exact(1)
.map_err(|_| InflateError::Allocation { attempted: size })?;
let mut chunk: Vec<u8> = Vec::new();
match chunk.try_reserve_exact(size) {
Ok(()) => {
chunk.resize(size, 0);
held_bytes = held_bytes.saturating_add(size);
chunks.push(chunk);
}
Err(_) if chunk_size > MIN_CHUNK_BYTES => {
chunk_size = (chunk_size / 2).max(MIN_CHUNK_BYTES);
}
Err(_) => {
tracing::warn!(
limit,
attempted = size,
held = held_bytes,
"memory inflation failed: even the minimum chunk could not be allocated before reaching the limit"
);
return Err(InflateError::Allocation { attempted: size });
}
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
use std::time::Duration;
use super::inflate;
use crate::memory::resident_bytes::{resident_bytes, status_field_bytes};
const CHILD_TIMEOUT: Duration = Duration::from_secs(120);
const CHILD_ENV: &str = "APOPTOSIS_TEST_INFLATE_CHILD";
const CHILD_EXTRA_ENV: &str = "APOPTOSIS_TEST_INFLATE_EXTRA_BYTES";
const CHILD_EXTRA_BYTES: u64 = 48 * 1024 * 1024;
const CHILD_HWM_TOLERANCE: u64 = 1024 * 1024;
#[tokio::test]
async fn inflate_skips_when_limit_not_above_usage() {
let Some(resident) = resident_bytes() else {
return;
};
assert_eq!(inflate(resident).await, Ok(()));
assert_eq!(inflate(resident / 2).await, Ok(()));
}
#[tokio::test]
#[ignore = "запускается только как дочерний процесс теста inflate_grows_resident_in_subprocess"]
async fn inflate_child_stub() {
if std::env::var(CHILD_ENV).as_deref() != Ok("1") {
return;
}
let extra: u64 = std::env::var(CHILD_EXTRA_ENV)
.map_err(|error| format!("env {CHILD_EXTRA_ENV} is missing: {error}"))
.and_then(|text| {
text.parse::<u64>()
.map_err(|error| format!("env {CHILD_EXTRA_ENV} is not a number: {error}"))
})
.expect("child process arguments are prepared by the parent test");
let before = resident_bytes().expect("child process reads resident usage");
let limit = before + extra;
let result = tokio::time::timeout(std::time::Duration::from_secs(60), inflate(limit))
.await
.expect("child process inflation finishes within the timeout");
let status = std::fs::read_to_string(crate::memory::resident_bytes::STATUS_PATH)
.expect("child process reads the status file");
let after = status_field_bytes(&status, "VmHWM:")
.expect("child process reads the peak resident usage");
println!("APOPTOSIS_BEFORE={before}");
println!("APOPTOSIS_AFTER={after}");
assert_eq!(result, Ok(()), "child inflation must succeed");
assert!(
after >= limit.saturating_sub(CHILD_HWM_TOLERANCE),
"peak resident usage must reach the limit {limit}: before={before}, after={after}"
);
}
#[test]
fn inflate_grows_resident_in_subprocess() {
let Ok(exe) = std::env::current_exe() else {
unreachable!("the test binary path is always available");
};
let full = concat!(module_path!(), "::inflate_child_stub");
let crate_prefix = concat!(env!("CARGO_CRATE_NAME"), "::");
let child_test = full.strip_prefix(crate_prefix).unwrap_or(full);
let mut child = std::process::Command::new(exe)
.arg(child_test)
.args(["--exact", "--ignored", "--nocapture"])
.env(CHILD_ENV, "1")
.env(CHILD_EXTRA_ENV, CHILD_EXTRA_BYTES.to_string())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("child test process spawns");
let deadline = std::time::Instant::now() + CHILD_TIMEOUT;
let status = loop {
match child.try_wait().expect("child process state is polled") {
Some(status) => break Some(status),
None if std::time::Instant::now() >= deadline => break None,
None => std::thread::sleep(std::time::Duration::from_millis(200)),
}
};
let Some(status) = status else {
let _ = child.kill();
panic!("child test process did not finish within the deadline");
};
let output = child
.wait_with_output()
.expect("child process output is collected");
let stdout = String::from_utf8_lossy(&output.stdout);
println!("{stdout}");
println!("{}", String::from_utf8_lossy(&output.stderr));
assert!(
status.success(),
"child test process must exit with code 0: {status:?}"
);
let Some(before) = parse_marker(&stdout, "APOPTOSIS_BEFORE=") else {
panic!("child stdout must contain the APOPTOSIS_BEFORE marker");
};
let Some(after) = parse_marker(&stdout, "APOPTOSIS_AFTER=") else {
panic!("child stdout must contain the APOPTOSIS_AFTER marker");
};
assert!(
after.saturating_sub(before) >= CHILD_EXTRA_BYTES - CHILD_HWM_TOLERANCE,
"resident usage must grow by at least {CHILD_EXTRA_BYTES} bytes (peak, with accounting tolerance): before={before}, after={after}"
);
}
fn parse_marker(stdout: &str, marker: &str) -> Option<u64> {
stdout
.lines()
.find_map(|line| line.strip_prefix(marker))
.and_then(|text| text.trim().parse().ok())
}
}