use super::{cell, fetch, matches_pattern, number_of, pairs, text_of, ServerSettings};
use crate::cli::server::StatusArgs;
use crate::error::{Failure, Result};
use crate::output::{Envelope, Gap, Row};
use indexmap::IndexMap;
use mysql_async::{Conn, Params};
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;
const UPTIME: &str = "Uptime";
pub async fn run(
connection: &mut Conn,
args: &StatusArgs,
settings: &ServerSettings,
token: &CancellationToken,
) -> Result<Envelope> {
let interval = args.interval.unwrap_or(settings.status_interval_secs);
let first = read_counters(connection).await?;
super::wait_interval(interval, token).await?;
let second = read_counters(connection).await?;
refuse_across_restart(&first, &second, interval)?;
let rows = compare(&first, &second, args.pattern.as_deref());
let (summary, gaps) = summarise(connection, &second).await;
let mut envelope = Envelope::new(
"server status",
json!({
"interval_secs": interval,
"summary": summary,
"rows": rows,
}),
);
for gap in gaps {
envelope = envelope.with_gap(gap);
}
Ok(envelope)
}
async fn read_counters(connection: &mut Conn) -> Result<IndexMap<String, String>> {
let rows = fetch(connection, "SHOW GLOBAL STATUS", Params::Empty).await?;
Ok(pairs(&rows))
}
pub fn refuse_across_restart(
first: &IndexMap<String, String>,
second: &IndexMap<String, String>,
interval: u64,
) -> Result<()> {
let before: Option<i64> = first.get(UPTIME).and_then(|text| text.parse().ok());
let after: Option<i64> = second.get(UPTIME).and_then(|text| text.parse().ok());
match (before, after) {
(Some(before), Some(after)) if after < before => Err(Failure::server(
"server.restarted_between_readings",
"the server restarted between the two readings, so no difference can be computed",
)
.with_detail("interval", interval.to_string())
.with_hint(format!(
"read again once the server is stable; the interval used was {interval} seconds"
))),
_ => Ok(()),
}
}
#[must_use]
pub fn compare(
first: &IndexMap<String, String>,
second: &IndexMap<String, String>,
pattern: Option<&str>,
) -> Vec<Row> {
let mut rows = Vec::new();
for (name, current) in second {
if pattern.is_some_and(|pattern| !matches_pattern(pattern, name)) {
continue;
}
let previous = first.get(name);
let mut row = Row::new();
row.insert("name".to_owned(), json!(name));
row.insert("value".to_owned(), json!(current));
row.insert("previous".to_owned(), json!(previous));
row.insert("delta".to_owned(), difference(previous, current));
rows.push(row);
}
rows
}
fn difference(previous: Option<&String>, current: &str) -> Value {
let before: Option<i64> = previous.and_then(|text| text.trim().parse().ok());
let after: Option<i64> = current.trim().parse().ok();
match (before, after) {
(Some(before), Some(after)) => json!(after - before),
_ => Value::Null,
}
}
async fn summarise(
connection: &mut Conn,
counters: &IndexMap<String, String>,
) -> (Value, Vec<Gap>) {
let mut gaps = Vec::new();
let in_use: i64 = read_counter(counters, "Threads_connected");
let running: i64 = read_counter(counters, "Threads_running");
let ceiling = match scalar(connection, "SELECT @@max_connections").await {
Ok(value) => value,
Err(failure) => {
gaps.push(Gap::new(
"connection_ceiling",
"unreadable",
failure.message().to_owned(),
));
Value::Null
}
};
let longest = match longest_statement(connection).await {
Ok(value) => value,
Err(failure) => {
gaps.push(Gap::new(
"longest_statement_seconds",
"permission",
failure.message().to_owned(),
));
Value::Null
}
};
let mut summary = json!({
"connections_in_use": in_use,
"connections_running": running,
"connections_idle": (in_use - running).max(0),
"connection_ceiling": ceiling,
"longest_statement_seconds": longest,
});
match page_cache(counters) {
Ok(cache) => summary["page_cache"] = cache,
Err(gap) => gaps.push(gap),
}
(summary, gaps)
}
fn page_cache(counters: &IndexMap<String, String>) -> std::result::Result<Value, Gap> {
const REQUESTS: &str = "Innodb_buffer_pool_read_requests";
const FROM_DISK: &str = "Innodb_buffer_pool_reads";
if !counters.contains_key(REQUESTS) && !counters.contains_key(FROM_DISK) {
return Err(Gap::new(
"page_cache",
"not_published",
"this server publishes neither page cache counter",
));
}
let requests = read_counter(counters, REQUESTS);
let from_disk = read_counter(counters, FROM_DISK);
let from_memory = (requests - from_disk).max(0);
let ratio = (requests > 0).then(|| {
let hundredths =
(i128::from(from_memory) * 20_000 + i128::from(requests)) / (i128::from(requests) * 2);
let written = format!("{}.{:02}", hundredths / 100, hundredths % 100);
serde_json::from_str::<serde_json::Value>(&written).unwrap_or(Value::Null)
});
Ok(json!({
"hit_ratio_pct": ratio,
"pages_from_memory": from_memory,
"pages_from_disk": from_disk,
}))
}
fn read_counter(counters: &IndexMap<String, String>, name: &str) -> i64 {
counters
.get(name)
.and_then(|text| text.trim().parse().ok())
.unwrap_or_default()
}
async fn longest_statement(connection: &mut Conn) -> Result<Value> {
let rows = fetch(
connection,
"SELECT MAX(TIME) FROM information_schema.PROCESSLIST WHERE COMMAND <> 'Sleep'",
Params::Empty,
)
.await
.map_err(|failure| super::observation_failure(failure, "PROCESS", "other-connections"))?;
Ok(rows
.first()
.and_then(|row| row.values().next())
.cloned()
.unwrap_or(Value::Null))
}
async fn scalar(connection: &mut Conn, sql: &str) -> Result<Value> {
let rows = fetch(connection, sql, Params::Empty).await?;
Ok(rows
.first()
.and_then(|row| row.values().next())
.cloned()
.unwrap_or(Value::Null))
}
#[must_use]
pub fn row_name(row: &Row) -> String {
text_of(cell(row, "name"))
}
#[must_use]
pub fn row_delta(row: &Row) -> Option<i64> {
number_of(cell(row, "delta"))
}
#[cfg(test)]
mod tests {
use super::*;
fn reading(pairs: &[(&str, &str)]) -> IndexMap<String, String> {
pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect()
}
#[test]
fn a_counter_reports_both_its_total_and_its_change() {
let first = reading(&[("Questions", "100")]);
let second = reading(&[("Questions", "142")]);
let rows = compare(&first, &second, None);
assert_eq!(rows.len(), 1);
assert_eq!(row_name(&rows[0]), "Questions");
assert_eq!(row_delta(&rows[0]), Some(42));
assert_eq!(rows[0]["value"], json!("142"));
assert_eq!(rows[0]["previous"], json!("100"));
}
#[test]
fn a_counter_that_is_not_a_number_gets_no_difference() {
let first = reading(&[("Rsa_public_key", "-----BEGIN")]);
let second = reading(&[("Rsa_public_key", "-----BEGIN")]);
let rows = compare(&first, &second, None);
assert_eq!(rows[0]["delta"], Value::Null);
}
#[test]
fn a_counter_absent_from_the_first_reading_gets_no_difference() {
let rows = compare(&reading(&[]), &reading(&[("New_counter", "5")]), None);
assert_eq!(rows[0]["delta"], Value::Null);
assert_eq!(rows[0]["previous"], Value::Null);
}
#[test]
fn the_pattern_narrows_the_counters() {
let first = reading(&[("Questions", "1"), ("Threads_connected", "3")]);
let second = reading(&[("Questions", "9"), ("Threads_connected", "4")]);
let rows = compare(&first, &second, Some("threads_%"));
assert_eq!(rows.len(), 1);
assert_eq!(row_name(&rows[0]), "Threads_connected");
}
#[test]
fn a_restart_between_readings_refuses_the_difference() {
let first = reading(&[(UPTIME, "9000")]);
let second = reading(&[(UPTIME, "4")]);
let failure =
refuse_across_restart(&first, &second, 5).expect_err("a restart must be refused");
assert_eq!(failure.exit_number().code(), 11);
assert!(failure.hint().is_some_and(|hint| hint.contains('5')));
}
#[test]
fn a_stable_server_allows_the_difference() {
let first = reading(&[(UPTIME, "9000")]);
let second = reading(&[(UPTIME, "9005")]);
assert!(refuse_across_restart(&first, &second, 5).is_ok());
}
}