Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)`.

Expand Down
7 changes: 7 additions & 0 deletions assets/ui.html
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,13 @@ <h2>Run a test</h2>
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`);
Expand Down
3 changes: 2 additions & 1 deletion book/src/endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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) |
Expand Down
2 changes: 1 addition & 1 deletion book/src/watch.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/cli/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ pub struct Memory {
pub limit_mb: i64,
pub process_rss_mb: i64,
pub container_limit_mb: Option<i64>,
/// Seconds until the last `/memory` or `/leak` lets go; a server that does not say, or holds nothing, has none
pub seconds_left: Option<i64>,
}

#[derive(Debug, Deserialize)]
Expand All @@ -60,12 +62,15 @@ pub struct Disk {
pub limit_mb: i64,
pub dir: String,
pub free_mb: Option<i64>,
pub seconds_left: Option<i64>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Connections {
pub held: i64,
pub limit: i64,
pub seconds_left: Option<i64>,
}

#[derive(Debug, Deserialize)]
Expand All @@ -74,6 +79,7 @@ pub struct Fd {
pub held: i64,
pub limit: i64,
pub process_limit: Option<i64>,
pub seconds_left: Option<i64>,
}

impl Fd {
Expand Down
44 changes: 44 additions & 0 deletions src/cli/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,29 @@ fn rows(style: &Style, info: &Info, history: &History) -> Vec<String> {
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 {
Expand All @@ -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));
}
Expand Down Expand Up @@ -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)));
}
Expand Down Expand Up @@ -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);
Expand Down
46 changes: 45 additions & 1 deletion src/resources/budget.rs
Original file line number Diff line number Diff line change
@@ -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<i64>,
// when each hold that is running lets go, to say how long the longest has left
ends: Mutex<Vec<(u64, Instant)>>,
next_end: AtomicU64,
}

/// What was asked does not fit in what is left
Expand All @@ -16,7 +21,7 @@ pub struct OverBudget {

impl Budget {
pub fn new(limit: i64) -> Arc<Budget> {
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 {
Expand All @@ -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<Self>, 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<u64> {
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<Self>, amount: i64) -> Result<Reservation, OverBudget> {
let mut held = self.held.lock().unwrap();
Expand All @@ -38,6 +57,18 @@ impl Budget {
}
}

#[must_use = "the end is forgotten as soon as this is dropped"]
pub struct Ending {
budget: Arc<Budget>,
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<Budget>,
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/resources/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
1 change: 1 addition & 0 deletions src/resources/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/resources/fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
3 changes: 3 additions & 0 deletions src/resources/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,15 @@ 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) => {
drop(reservation);
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);
Expand Down Expand Up @@ -80,6 +82,7 @@ impl Memory {
break;
}
}
let _ending = leak.budget.ends_in(seconds);
tokio::time::sleep(Duration::from_secs(seconds)).await;
drop(leak);
});
Expand Down
6 changes: 4 additions & 2 deletions src/routes/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,17 @@ pub async fn handler(State(state): State<Arc<AppState>>) -> Json<Value> {
"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),
Expand Down
20 changes: 18 additions & 2 deletions src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,30 @@ pub struct Memory {
pub limit_mb: i64,
pub rss_bytes: u64,
pub container_limit_bytes: Option<u64>,
/// Seconds until the last `/memory` or `/leak` lets go, `None` when nothing is held
pub seconds_left: Option<u64>,
}

pub struct Disk {
pub held_mb: i64,
pub limit_mb: i64,
pub dir: String,
pub free_bytes: Option<u64>,
pub seconds_left: Option<u64>,
}

pub struct Fd {
pub held: i64,
pub limit: i64,
/// What the process can open at all (`ulimit -n`), which may be lower than `limit`
pub process_limit: Option<u64>,
pub seconds_left: Option<u64>,
}

pub struct Connections {
pub held: i64,
pub limit: i64,
pub seconds_left: Option<u64>,
}

pub struct Snapshot {
Expand All @@ -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(),
Expand Down
4 changes: 2 additions & 2 deletions tests/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
Loading
Loading