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

83 lines
1.7 KiB
Rust
Raw Normal View History

use chrono::{DateTime, Utc};
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 PerInstance {
// 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,
pub startup_utc: DateTime <Utc>,
}
#[derive (Debug, serde::Serialize)]
pub struct Gauges {
pub rss_mib: u64,
}
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 PerInstance {
#[must_use]
pub fn new (server_name: String) -> Self
{
Self {
machine_id: get_machine_id (),
git_version: None,
server_name,
instance_id: ulid::Ulid::new (),
startup_utc: Utc::now (),
}
}
}
#[cfg (test)]
mod tests {
use super::*;
#[test]
fn ulid_null () {
let a = PerInstance::new ("bogus".to_string ());
let b = PerInstance::new ("bogus".to_string ());
assert_ne! (a.instance_id, b.instance_id);
}
}