ptth/crates/ptth_server/src/file_server/metrics.rs

143 lines
2.9 KiB
Rust

use chrono::{DateTime, Utc};
use tracing::debug;
use ulid::Ulid;
fn serialize_ulid <S: serde::Serializer> (t: &Ulid, s: S)
-> Result <S::Ok, S::Error>
{
let t = t.to_string ();
s.serialize_str (&t)
}
// Instance metrics are captured when the ptth_server process starts.
// They don't change after that.
#[derive (Debug, serde::Serialize)]
pub struct Startup {
// D-Bus machine ID, if we're on Linux
pub machine_id: Option <String>,
// Git version that ptth_server was built from (unimplemented)
pub git_version: Option <String>,
// User-assigned and human-readable name for this server.
// Must be unique within a relay.
pub server_name: String,
// Random base64 instance ID. ptth_server generates this at process start.
// It's a fallback for detecting outages without relying on any clocks.
#[serde (serialize_with = "serialize_ulid")]
pub instance_id: Ulid,
// System UTC
pub startup_utc: DateTime <Utc>,
}
// Gauges are things we instananeously measure on a fixed interval.
// They are not read back and accumulated like counters.
#[derive (Debug, serde::Serialize)]
pub struct Gauges {
pub utc: DateTime <Utc>,
pub rss_mib: u64,
// What's the difference?
pub cpu_time_user: f64,
pub cpu_time_system: f64,
#[serde (skip)]
pub cpu_usage: heim::process::CpuUsage,
}
impl Gauges {
pub async fn new () -> Result <Self, super::FileServerError> {
use tokio::join;
use heim::process;
use uom::si::{
information::mebibyte,
ratio,
time::second,
};
let our_process = process::current ().await?;
let cpu_time = our_process.cpu_time ();
let cpu_usage = our_process.cpu_usage ();
let (cpu_time, cpu_usage) = join! (
cpu_time,
cpu_usage,
);
let cpu_time = cpu_time?;
let cpu_time_user = cpu_time.user ().get::<second> ();
let cpu_time_system = cpu_time.system ().get::<second> ();
let cpu_usage = cpu_usage?;
let mem = our_process.memory ().await?;
let rss_mib = mem.rss ().get::<mebibyte> ();
let x = Gauges {
utc: Utc::now (),
rss_mib,
cpu_time_user,
cpu_time_system,
cpu_usage,
};
debug! ("metric gauges: {:?}", x);
Ok (x)
}
}
fn get_machine_id () -> Option <String> {
use std::{
fs::File,
io::Read,
};
let mut buf = vec! [0; 1024];
let mut f = File::open ("/etc/machine-id").ok ()?;
let bytes_read = f.read (&mut buf).ok ()?;
buf.truncate (bytes_read);
let s = std::str::from_utf8 (&buf).ok ()?;
let s = s.trim_end ().to_string ();
Some (s)
}
impl Startup {
#[must_use]
pub fn new (server_name: String) -> Self
{
let x = Self {
machine_id: get_machine_id (),
git_version: None,
server_name,
instance_id: ulid::Ulid::new (),
startup_utc: Utc::now (),
};
debug! ("metrics at startup: {:?}", x);
x
}
}
#[cfg (test)]
mod tests {
use super::*;
#[test]
fn ulid_null () {
let a = Startup::new ("bogus".to_string ());
let b = Startup::new ("bogus".to_string ());
assert_ne! (a.instance_id, b.instance_id);
}
}