diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2fb87f3..20ccf17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,9 @@ All notable changes to this project are documented here. The GitHub release of e
## Unreleased
+### Added
+- `watch` and the control panel have a line for each `/memory`, `/leak`, `/disk`, `/fd` and `/connections` that is holding something, with what it holds and the seconds left (`/memory: 100 MB, 18 s left`), as `/cpu` already had. `/info` reports it as `secondsLeft` in `memory`, `disk`, `fd` and `connections` (`null` when nothing is held), the time until the last hold of that resource lets go.
+
### Changed
- `/info` reports the limit of descriptors of the process (`fd.processLimit`, the soft `ulimit -n`), and the descriptors bar of `watch` and of the control panel compares with the lower of that and `MAX_FD`, so it is full when `EMFILE` comes and not at a quarter of a limit the process can't reach. `watch` marks it with `(ulimit)`.
diff --git a/assets/ui.html b/assets/ui.html
index 3a91ae8..520c103 100644
--- a/assets/ui.html
+++ b/assets/ui.html
@@ -631,6 +631,13 @@
Run a test
const n = info.stress.burn.workers ?? info.stress.workers;
status.unshift(`/cpu: ${info.stress.burn.percent}% on ${n < info.stress.workers ? `${n} of ${info.stress.workers} workers` : 'every worker'}, ${info.stress.burn.secondsLeft} s left`);
}
+ const holds = [
+ ['/memory', info.memory.secondsLeft, `${info.memory.heldMb} MB`],
+ ['/disk', info.disk.secondsLeft, `${info.disk.heldMb} MB`],
+ ['/fd', info.fd && info.fd.secondsLeft, info.fd && info.fd.held],
+ ['/connections', info.connections && info.connections.secondsLeft, info.connections && info.connections.held],
+ ];
+ for (const [path, left, held] of holds.reverse()) if (left != null) status.unshift(`${path}: ${held}, ${left} s left`);
if (info.scenario && info.scenario.state === 'running') status.unshift(`/scenario: step ${info.scenario.step} of ${info.scenario.steps}, ${info.scenario.remainingSeconds} s left`);
if ($('scenario-now')) $('scenario-now').textContent = scenarioText(info.scenario);
if (info.log) status.unshift(`/log: ${info.log.sent} of ${info.log.lines} lines, ${info.log.rate} lines/s`);
diff --git a/book/src/endpoints.md b/book/src/endpoints.md
index 238573a..ef555a3 100644
--- a/book/src/endpoints.md
+++ b/book/src/endpoints.md
@@ -301,7 +301,7 @@ Returns a JSON document with what the server is doing right now. It takes no par
"delay": { "inFlight": 3 },
"memory": { "heldMb": 200, "limitMb": 512, "processRssMb": 310, "containerLimitMb": 256 },
"disk": { "heldMb": 100, "limitMb": 1024, "dir": "/tmp", "freeMb": 8120 },
- "fd": { "held": 0, "limit": 10000, "processLimit": 1048576 },
+ "fd": { "held": 0, "limit": 10000, "processLimit": 1048576, "secondsLeft": null },
"ready": { "ready": true, "secondsLeft": null },
"log": null,
"limits": { "maxNumber": 50, "maxDelayMs": 60000, "maxHoldSeconds": 300, "maxLogLines": 100000, "maxLogRate": 10000 }
@@ -316,6 +316,7 @@ Returns a JSON document with what the server is doing right now. It takes no par
| `memory.heldMb`, `limitMb` | Memory held by `/memory` and the total it may hold (`MAX_MEMORY_MB`); the difference is what a new request can still allocate |
| `memory.processRssMb` | Memory the whole process uses, the figure that counts for an OOM kill |
| `memory.containerLimitMb` | Memory limit of the container, `null` when there is none |
+| `memory.secondsLeft`, `disk.secondsLeft`, `fd.secondsLeft`, `connections.secondsLeft` | Seconds until the last hold of that resource lets go, `null` when nothing is held |
| `disk.heldMb`, `limitMb` | Same as for memory, for `/disk` (`MAX_DISK_MB`) |
| `disk.freeMb` | Free space in `DISK_DIR`, `null` if the directory is not usable |
| `fd.held`, `limit`, `processLimit` | File descriptors held by `/fd`, the total it may hold (`MAX_FD`) and the limit of the process itself (`ulimit -n`, `null` when it has none) |
diff --git a/book/src/watch.md b/book/src/watch.md
index cb8b70a..c0a51f2 100644
--- a/book/src/watch.md
+++ b/book/src/watch.md
@@ -1,6 +1,6 @@
# Watching a server
-`torchio watch` shows what a server is doing in the terminal, refreshing every second with bars and a short history of the last samples (workers, memory, process memory, disk and file descriptors), plus whether `/ready` is answering `200` or `503`, and a line for the [scenario](scenarios.md) while one runs or after it ends. It is a command of the same binary, reads [`/info`](endpoints.md#info) and works against any running instance:
+`torchio watch` shows what a server is doing in the terminal, refreshing every second with bars and a short history of the last samples (workers, memory, process memory, disk and file descriptors), plus whether `/ready` is answering `200` or `503`, a line for each `/cpu`, `/memory`, `/disk`, `/fd` and `/connections` that is running with the seconds it has left (`/memory: 100 MB, 18 s left`), and a line for the [scenario](scenarios.md) while one runs or after it ends. It is a command of the same binary, reads [`/info`](endpoints.md#info) and works against any running instance:
```
torchio watch
diff --git a/src/cli/info.rs b/src/cli/info.rs
index ba3b564..21a4515 100644
--- a/src/cli/info.rs
+++ b/src/cli/info.rs
@@ -51,6 +51,8 @@ pub struct Memory {
pub limit_mb: i64,
pub process_rss_mb: i64,
pub container_limit_mb: Option,
+ /// Seconds until the last `/memory` or `/leak` lets go; a server that does not say, or holds nothing, has none
+ pub seconds_left: Option,
}
#[derive(Debug, Deserialize)]
@@ -60,12 +62,15 @@ pub struct Disk {
pub limit_mb: i64,
pub dir: String,
pub free_mb: Option,
+ pub seconds_left: Option,
}
#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
pub struct Connections {
pub held: i64,
pub limit: i64,
+ pub seconds_left: Option,
}
#[derive(Debug, Deserialize)]
@@ -74,6 +79,7 @@ pub struct Fd {
pub held: i64,
pub limit: i64,
pub process_limit: Option,
+ pub seconds_left: Option,
}
impl Fd {
diff --git a/src/cli/view.rs b/src/cli/view.rs
index bfc19ae..3f033fb 100644
--- a/src/cli/view.rs
+++ b/src/cli/view.rs
@@ -267,6 +267,29 @@ fn rows(style: &Style, info: &Info, history: &History) -> Vec {
rows
}
+/// What `/memory`, `/leak`, `/disk`, `/fd` and `/connections` hold right now and for how long more:
+/// the colour of its line, its command, and the text
+fn holds(info: &Info) -> Vec<(u8, &'static str, String)> {
+ let mut holds = Vec::new();
+ if let Some(left) = info.memory.seconds_left {
+ holds.push((114, "/memory", format!("{} MB, {left} s left", info.memory.held_mb)));
+ }
+ if let Some(left) = info.disk.seconds_left {
+ holds.push((180, "/disk", format!("{} MB, {left} s left", info.disk.held_mb)));
+ }
+ if let Some(fd) = &info.fd
+ && let Some(left) = fd.seconds_left
+ {
+ holds.push((141, "/fd", format!("{}, {left} s left", fd.held)));
+ }
+ if let Some(connections) = &info.connections
+ && let Some(left) = connections.seconds_left
+ {
+ holds.push((75, "/connections", format!("{}, {left} s left", connections.held)));
+ }
+ holds
+}
+
/// The view of the last sample, with the history of the previous ones
pub fn render(style: &Style, url: &str, info: &Info, history: &History) -> String {
if style.color {
@@ -280,6 +303,9 @@ pub fn render(style: &Style, url: &str, info: &Info, history: &History) -> Strin
if let Some(burn) = &info.stress.burn {
lines.push(format!("/cpu: {}% on {}, {} s left", burn.percent, burned(info, burn), burn.seconds_left));
}
+ for (_, command, text) in holds(info) {
+ lines.push(format!("{command}: {text}"));
+ }
if let Some(log) = &info.log {
lines.push(format!("/log: {} of {} lines, {} lines/s", log.sent, log.lines, log.rate));
}
@@ -333,6 +359,9 @@ fn render_color(style: &Style, url: &str, info: &Info, history: &History) -> Str
}
None => lines.push(activity(false, 209, "/cpu idle".into())),
}
+ for (color, command, text) in holds(info) {
+ lines.push(activity(true, color, format!("{command} {text}")));
+ }
if let Some(log) = &info.log {
lines.push(activity(true, 177, format!("/log {} of {} lines, {} lines/s", log.sent, log.lines, log.rate)));
}
@@ -387,6 +416,21 @@ mod tests {
assert!(plain(&none).contains("40 / 10000") && !plain(&none).contains("ulimit"), "no limit of the process changes nothing");
}
+ #[test]
+ fn every_hold_that_runs_has_a_line_with_the_seconds_left() {
+ let busy = INFO
+ .replace("\"containerLimitMb\": 256", "\"containerLimitMb\": 256, \"secondsLeft\": 18")
+ .replace("\"freeMb\": null", "\"freeMb\": null, \"secondsLeft\": 9")
+ .replace("\"fd\": {\"held\": 40, \"limit\": 10000}", "\"fd\": {\"held\": 40, \"limit\": 10000, \"secondsLeft\": 5}");
+ let view = plain(&busy);
+ assert!(view.contains("\n/memory: 150 MB, 18 s left\n"), "{view}");
+ assert!(view.contains("\n/disk: 0 MB, 9 s left\n"), "{view}");
+ assert!(view.contains("\n/fd: 40, 5 s left\n"), "{view}");
+ assert!(!view.contains("/connections:"), "what is not held has no line");
+ let idle = plain(INFO);
+ assert!(!idle.contains("/memory:") && !idle.contains("/disk:") && !idle.contains("/fd:"), "{idle}");
+ }
+
#[test]
fn the_view_has_every_figure() {
let view = plain(INFO);
diff --git a/src/resources/budget.rs b/src/resources/budget.rs
index 608df2a..5cc851f 100644
--- a/src/resources/budget.rs
+++ b/src/resources/budget.rs
@@ -1,10 +1,15 @@
//! A total that concurrent requests share: what is held right now against a limit, so they
//! can't grow it unbounded.
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
pub struct Budget {
limit: i64,
held: Mutex,
+ // when each hold that is running lets go, to say how long the longest has left
+ ends: Mutex>,
+ next_end: AtomicU64,
}
/// What was asked does not fit in what is left
@@ -16,7 +21,7 @@ pub struct OverBudget {
impl Budget {
pub fn new(limit: i64) -> Arc {
- Arc::new(Budget { limit, held: Mutex::new(0) })
+ Arc::new(Budget { limit, held: Mutex::new(0), ends: Mutex::new(Vec::new()), next_end: AtomicU64::new(0) })
}
pub fn limit(&self) -> i64 {
@@ -27,6 +32,20 @@ impl Budget {
*self.held.lock().unwrap()
}
+ /// Notes that a hold lets go in `seconds`, until the returned value is dropped
+ pub fn ends_in(self: &Arc, seconds: u64) -> Ending {
+ let id = self.next_end.fetch_add(1, Ordering::Relaxed);
+ self.ends.lock().unwrap().push((id, Instant::now() + Duration::from_secs(seconds)));
+ Ending { budget: Arc::clone(self), id }
+ }
+
+ /// Seconds until the last of the running holds lets go, rounded up; `None` when nothing is held
+ pub fn seconds_left(&self) -> Option {
+ let now = Instant::now();
+ let last = self.ends.lock().unwrap().iter().map(|(_, end)| *end).max()?;
+ Some(last.saturating_duration_since(now).as_millis().div_ceil(1000) as u64)
+ }
+
/// Reserves `amount` until the reservation is dropped
pub fn reserve(self: &Arc, amount: i64) -> Result {
let mut held = self.held.lock().unwrap();
@@ -38,6 +57,18 @@ impl Budget {
}
}
+#[must_use = "the end is forgotten as soon as this is dropped"]
+pub struct Ending {
+ budget: Arc,
+ id: u64,
+}
+
+impl Drop for Ending {
+ fn drop(&mut self) {
+ self.budget.ends.lock().unwrap().retain(|(id, _)| *id != self.id);
+ }
+}
+
#[must_use = "a reservation is given back as soon as it is dropped"]
pub struct Reservation {
budget: Arc,
@@ -64,6 +95,19 @@ impl Drop for Reservation {
mod tests {
use super::*;
+ #[test]
+ fn the_longest_hold_says_how_long_is_left_and_nothing_held_says_nothing() {
+ let budget = Budget::new(10);
+ assert_eq!(budget.seconds_left(), None);
+ let short = budget.ends_in(5);
+ let long = budget.ends_in(30);
+ assert_eq!(budget.seconds_left(), Some(30));
+ drop(long);
+ assert_eq!(budget.seconds_left(), Some(5));
+ drop(short);
+ assert_eq!(budget.seconds_left(), None);
+ }
+
#[test]
fn reserves_up_to_the_limit_and_gives_back_on_drop() {
let budget = Budget::new(300);
diff --git a/src/resources/connections.rs b/src/resources/connections.rs
index 4562aeb..ae78fb5 100644
--- a/src/resources/connections.rs
+++ b/src/resources/connections.rs
@@ -48,8 +48,10 @@ impl Connections {
reservation.shrink_to(streams.len() as i64);
let opened = streams.len();
+ let ending = self.budget.ends_in(seconds);
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(seconds)).await;
+ drop(ending);
drop(streams);
drop(reservation);
});
diff --git a/src/resources/disk.rs b/src/resources/disk.rs
index 9b1469f..869e0ed 100644
--- a/src/resources/disk.rs
+++ b/src/resources/disk.rs
@@ -71,6 +71,7 @@ impl Disk {
let failed = result.is_err();
let _ = written.send(result);
if !failed {
+ let _ending = disk.budget.ends_in(seconds);
tokio::time::sleep(Duration::from_secs(seconds)).await;
}
disk.files.lock().unwrap().remove(&file);
diff --git a/src/resources/fd.rs b/src/resources/fd.rs
index a0ead63..d474bb2 100644
--- a/src/resources/fd.rs
+++ b/src/resources/fd.rs
@@ -46,8 +46,10 @@ impl Fd {
reservation.shrink_to(files.len() as i64);
let opened = files.len();
+ let ending = self.budget.ends_in(seconds);
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(seconds)).await;
+ drop(ending);
drop(files);
drop(reservation);
});
diff --git a/src/resources/memory.rs b/src/resources/memory.rs
index b5526fd..5ce7a33 100644
--- a/src/resources/memory.rs
+++ b/src/resources/memory.rs
@@ -46,6 +46,7 @@ impl Memory {
pub async fn hold(&self, mb: i64, seconds: u64) -> Result<(), HoldError> {
let reservation = self.budget.reserve(mb).map_err(HoldError::OverBudget)?;
let (allocated, answer) = oneshot::channel();
+ let budget = Arc::clone(&self.budget);
tokio::spawn(async move {
match allocate_blocking(mb).await {
Err(e) => {
@@ -53,6 +54,7 @@ impl Memory {
let _ = allocated.send(Err(e));
}
Ok(held) => {
+ let _ending = budget.ends_in(seconds);
let _ = allocated.send(Ok(()));
tokio::time::sleep(Duration::from_secs(seconds)).await;
drop(held);
@@ -80,6 +82,7 @@ impl Memory {
break;
}
}
+ let _ending = leak.budget.ends_in(seconds);
tokio::time::sleep(Duration::from_secs(seconds)).await;
drop(leak);
});
diff --git a/src/routes/info.rs b/src/routes/info.rs
index d285b0d..99393bf 100644
--- a/src/routes/info.rs
+++ b/src/routes/info.rs
@@ -29,15 +29,17 @@ pub async fn handler(State(state): State>) -> Json {
"limitMb": snapshot.memory.limit_mb,
"processRssMb": to_mb(snapshot.memory.rss_bytes),
"containerLimitMb": snapshot.memory.container_limit_bytes.map(to_mb),
+ "secondsLeft": snapshot.memory.seconds_left,
},
"disk": {
"heldMb": snapshot.disk.held_mb,
"limitMb": snapshot.disk.limit_mb,
"dir": snapshot.disk.dir,
"freeMb": snapshot.disk.free_bytes.map(to_mb),
+ "secondsLeft": snapshot.disk.seconds_left,
},
- "fd": {"held": snapshot.fd.held, "limit": snapshot.fd.limit, "processLimit": snapshot.fd.process_limit},
- "connections": {"held": snapshot.connections.held, "limit": snapshot.connections.limit},
+ "fd": {"held": snapshot.fd.held, "limit": snapshot.fd.limit, "processLimit": snapshot.fd.process_limit, "secondsLeft": snapshot.fd.seconds_left},
+ "connections": {"held": snapshot.connections.held, "limit": snapshot.connections.limit, "secondsLeft": snapshot.connections.seconds_left},
"ready": snapshot.ready,
"block": snapshot.block,
"scenario": state.scenario.snapshot(false),
diff --git a/src/snapshot.rs b/src/snapshot.rs
index 877c63e..fed39b3 100644
--- a/src/snapshot.rs
+++ b/src/snapshot.rs
@@ -12,6 +12,8 @@ pub struct Memory {
pub limit_mb: i64,
pub rss_bytes: u64,
pub container_limit_bytes: Option,
+ /// Seconds until the last `/memory` or `/leak` lets go, `None` when nothing is held
+ pub seconds_left: Option,
}
pub struct Disk {
@@ -19,6 +21,7 @@ pub struct Disk {
pub limit_mb: i64,
pub dir: String,
pub free_bytes: Option,
+ pub seconds_left: Option,
}
pub struct Fd {
@@ -26,11 +29,13 @@ pub struct Fd {
pub limit: i64,
/// What the process can open at all (`ulimit -n`), which may be lower than `limit`
pub process_limit: Option,
+ pub seconds_left: Option,
}
pub struct Connections {
pub held: i64,
pub limit: i64,
+ pub seconds_left: Option,
}
pub struct Snapshot {
@@ -56,15 +61,26 @@ impl AppState {
limit_mb: self.memory.budget().limit(),
rss_bytes: system::rss_bytes(),
container_limit_bytes: system::container_limit_bytes(),
+ seconds_left: self.memory.budget().seconds_left(),
},
disk: Disk {
held_mb: self.disk.budget().held(),
limit_mb: self.disk.budget().limit(),
dir: self.config.disk_dir.clone(),
free_bytes: system::free_bytes(&self.config.disk_dir),
+ seconds_left: self.disk.budget().seconds_left(),
+ },
+ fd: Fd {
+ held: self.fd.budget().held(),
+ limit: self.fd.budget().limit(),
+ process_limit: system::fd_limit(),
+ seconds_left: self.fd.budget().seconds_left(),
+ },
+ connections: Connections {
+ held: self.connections.budget().held(),
+ limit: self.connections.budget().limit(),
+ seconds_left: self.connections.budget().seconds_left(),
},
- fd: Fd { held: self.fd.budget().held(), limit: self.fd.budget().limit(), process_limit: system::fd_limit() },
- connections: Connections { held: self.connections.budget().held(), limit: self.connections.budget().limit() },
ready: self.ready.state(),
block: self.block.snapshot(),
log: self.log.state(),
diff --git a/tests/api.rs b/tests/api.rs
index 6003c87..4a71bef 100644
--- a/tests/api.rs
+++ b/tests/api.rs
@@ -327,8 +327,8 @@ async fn info_has_these_fields() {
]
);
assert_eq!(keys(&info["stress"]), ["burn", "inFlight", "perWorker", "workers"]);
- assert_eq!(keys(&info["memory"]), ["containerLimitMb", "heldMb", "limitMb", "processRssMb"]);
- assert_eq!(keys(&info["disk"]), ["dir", "freeMb", "heldMb", "limitMb"]);
+ assert_eq!(keys(&info["memory"]), ["containerLimitMb", "heldMb", "limitMb", "processRssMb", "secondsLeft"]);
+ assert_eq!(keys(&info["disk"]), ["dir", "freeMb", "heldMb", "limitMb", "secondsLeft"]);
assert_eq!(keys(&info["ready"]), ["ready", "secondsLeft"]);
assert_eq!(keys(&info["block"]), ["count", "lastMs", "msLeft"]);
assert_eq!(
diff --git a/tests/observability.rs b/tests/observability.rs
index 8001764..11ffa77 100644
--- a/tests/observability.rs
+++ b/tests/observability.rs
@@ -50,6 +50,24 @@ fn info_follows_what_the_server_holds() {
assert_eq!(info["fd"]["held"], 20);
}
+#[test]
+fn info_says_how_long_is_left_of_each_hold_and_nothing_when_nothing_is_held() {
+ let server = Server::start();
+ let idle = server.info();
+ for key in ["memory", "disk", "fd", "connections"] {
+ assert!(idle[key]["secondsLeft"].is_null(), "{key}: {}", idle[key]);
+ }
+ server.get("/memory?mb=10&hold=30");
+ server.get("/disk?mb=1&hold=20");
+ server.get("/fd?count=5&hold=10");
+ server.get("/connections?count=3&hold=8");
+ let info = server.info();
+ for (key, most) in [("memory", 30), ("disk", 20), ("fd", 10), ("connections", 8)] {
+ let left = info[key]["secondsLeft"].as_i64().unwrap_or_else(|| panic!("{key}: {}", info[key]));
+ assert!((most - 2..=most).contains(&left), "{key} has {left} s left of {most}");
+ }
+}
+
// Every sample must come after the TYPE of its metric, and be a name and a number
fn check_prometheus_text(body: &str) {
assert!(body.ends_with('\n'));