aboutsummaryrefslogtreecommitdiff
path: root/crates/whirl_api/src/routes/stats/mod.rs
blob: 595b4419e89e8e4d05a68e13bf932660b7fd59c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright (C) 2021-2021 The Whirlsplash Collective
// SPDX-License-Identifier: GPL-3.0-only

pub mod structures;

use std::convert::TryFrom;

use axum::response;
use num_traits::cast::AsPrimitive;
use sysinfo::{get_current_pid, ProcessExt, System, SystemExt};

use crate::routes::stats::structures::{Statistics, StatisticsProcess, StatisticsSystem};

// This is mostly for developmental testing, it consumes more CPU than it's
// worth.
#[allow(clippy::unused_async)]
pub async fn statistics() -> impl response::IntoResponse {
  let mut sys = System::new_all();
  sys.refresh_all();

  let process = sys.process(get_current_pid().unwrap()).unwrap();

  (
    hyper::StatusCode::OK,
    response::Json(Statistics {
      system:  StatisticsSystem {
        os_type: sys.name().unwrap(),
        release: sys.kernel_version().unwrap(),
        uptime:  whirl_common::system::unixts_to_hrtime(usize::try_from(sys.uptime()).unwrap()),
      },
      process: StatisticsProcess {
        // (process.cpu_usage() * 100.0).round() / 100.0
        memory_usage: (process.memory() / 1000).to_string(),
        cpu_usage:    (process.cpu_usage() / sys.processors().len().as_(): f32).to_string(),
        // uptime: seconds_to_hrtime((sys.get_uptime() - process.start_time()) as usize),
      },
    }),
  )
}