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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use rust_decimal::prelude::*;
use serde::Deserialize;
use serde::Serialize;
use std::net::UdpSocket;
use std::time::{SystemTime, UNIX_EPOCH};

/// 网络传输结构体
#[derive(Serialize, Deserialize, Debug)]
pub struct WebResult<T> {
    pub data: Option<T>,
    pub code: usize,
    pub msg: Option<String>,
}

/// WebResult functions
impl <T>WebResult<T> {
    pub fn success(data: T) -> WebResult<T> {
        let result: WebResult<T> = WebResult {
            data: Some(data),
            code: 200,
            msg: Some("success".to_string()),
        };
        result
    }
}

/// 系统监控指标
#[derive(Serialize, Deserialize, Debug)]
pub struct MonitorRecord {
    #[serde(with = "rust_decimal::serde::float")]
    pub cpu_per: Decimal,
    #[serde(with = "rust_decimal::serde::float")]
    pub mem_per: Decimal,
    #[serde(with = "rust_decimal::serde::float")]
    pub recv_rate: Decimal,
    #[serde(with = "rust_decimal::serde::float")]
    pub sent_rate: Decimal,
    pub tcp_total: usize,
    pub io_reads: u64,
    pub io_writes: u64,
    pub node_ip: String,
    pub timestamp: u64,
    pub group_name: String,
}

/// 系统信息结构体
#[derive(Serialize, Deserialize, Debug)]
pub struct SysInfoRecord {
    pub boot_time_sec: i64,
    pub cpu_num: u32,
    pub cpu_speed: u64,
    pub mem_total: u64,
    pub disk_total: u64,
    pub disk_free: u64,
    pub hostname: String,
    pub os_name: String,
    pub load_avg_one: f64,
    pub proc_total: u64,
    pub node_ip: String,
    pub timestamp: u64,
    pub group_name: String,
}

/// 获取本机IP
pub fn get_local_ip() -> String {
    let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
    socket.connect("8.8.8.8:80").unwrap();
    socket.local_addr().unwrap().ip().to_string()
}

/// 获取时间戳
/// > 精确到秒,非毫秒
pub async fn get_timestamp() -> u64 {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    let timestamp = since_the_epoch.as_secs();
    timestamp
}

/// Get deploy time line
pub async fn get_time_line() -> u64 {
    let timestamp = get_timestamp().await;
    let time_line = timestamp - 2 * 3600;
    time_line
}