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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::sync::LazyLock;

use regex::Regex;
use serde::{
    de::{self, Error, MapAccess, Unexpected, Visitor},
    Deserialize, Deserializer,
};

use crate::event::{Metric, MetricKind, MetricTags, MetricValue};

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Stats {
    pub proc: Proc,
    pub sys: Sys,
}

impl Stats {
    pub fn metrics(&self, namespace: Option<String>) -> Vec<Metric> {
        let mut result = Vec::new();
        let mut tags = MetricTags::default();
        let now = chrono::Utc::now();
        let namespace = namespace.unwrap_or_else(|| "eventstoredb".to_string());

        tags.replace("id".to_string(), self.proc.id.to_string());

        result.push(
            Metric::new(
                "process_memory_used_bytes",
                MetricKind::Absolute,
                MetricValue::Gauge {
                    value: self.proc.mem as f64,
                },
            )
            .with_namespace(Some(namespace.clone()))
            .with_tags(Some(tags.clone()))
            .with_timestamp(Some(now)),
        );

        result.push(
            Metric::new(
                "disk_read_bytes_total",
                MetricKind::Absolute,
                MetricValue::Counter {
                    value: self.proc.disk_io.read_bytes as f64,
                },
            )
            .with_namespace(Some(namespace.clone()))
            .with_tags(Some(tags.clone()))
            .with_timestamp(Some(now)),
        );

        result.push(
            Metric::new(
                "disk_written_bytes_total",
                MetricKind::Absolute,
                MetricValue::Counter {
                    value: self.proc.disk_io.written_bytes as f64,
                },
            )
            .with_namespace(Some(namespace.clone()))
            .with_tags(Some(tags.clone()))
            .with_timestamp(Some(now)),
        );

        result.push(
            Metric::new(
                "disk_read_ops_total",
                MetricKind::Absolute,
                MetricValue::Counter {
                    value: self.proc.disk_io.read_ops as f64,
                },
            )
            .with_namespace(Some(namespace.clone()))
            .with_tags(Some(tags.clone()))
            .with_timestamp(Some(now)),
        );

        result.push(
            Metric::new(
                "disk_write_ops_total",
                MetricKind::Absolute,
                MetricValue::Counter {
                    value: self.proc.disk_io.write_ops as f64,
                },
            )
            .with_namespace(Some(namespace.clone()))
            .with_tags(Some(tags.clone()))
            .with_timestamp(Some(now)),
        );

        result.push(
            Metric::new(
                "memory_free_bytes",
                MetricKind::Absolute,
                MetricValue::Gauge {
                    value: self.sys.free_mem as f64,
                },
            )
            .with_namespace(Some(namespace.clone()))
            .with_tags(Some(tags.clone()))
            .with_timestamp(Some(now)),
        );

        if let Some(drive) = self.sys.drive.as_ref() {
            tags.replace("path".to_string(), drive.path.clone());

            result.push(
                Metric::new(
                    "disk_total_bytes",
                    MetricKind::Absolute,
                    MetricValue::Gauge {
                        value: drive.stats.total_bytes as f64,
                    },
                )
                .with_namespace(Some(namespace.clone()))
                .with_tags(Some(tags.clone()))
                .with_timestamp(Some(now)),
            );

            result.push(
                Metric::new(
                    "disk_free_bytes",
                    MetricKind::Absolute,
                    MetricValue::Gauge {
                        value: drive.stats.available_bytes as f64,
                    },
                )
                .with_namespace(Some(namespace.clone()))
                .with_tags(Some(tags.clone()))
                .with_timestamp(Some(now)),
            );

            result.push(
                Metric::new(
                    "disk_used_bytes",
                    MetricKind::Absolute,
                    MetricValue::Gauge {
                        value: drive.stats.used_bytes as f64,
                    },
                )
                .with_namespace(Some(namespace))
                .with_tags(Some(tags))
                .with_timestamp(Some(now)),
            );
        }

        result
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Proc {
    pub id: usize,
    pub mem: usize,
    pub cpu: f64,
    pub threads_count: i64,
    pub thrown_exceptions_rate: f64,
    pub disk_io: DiskIo,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DiskIo {
    pub read_bytes: usize,
    pub written_bytes: usize,
    pub read_ops: usize,
    pub write_ops: usize,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Sys {
    pub free_mem: usize,
    pub loadavg: LoadAvg,
    pub drive: Option<Drive>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LoadAvg {
    #[serde(rename = "1m")]
    pub one_m: f64,
    #[serde(rename = "5m")]
    pub five_m: f64,
    #[serde(rename = "15m")]
    pub fifteen_m: f64,
}

#[derive(Debug)]
pub struct Drive {
    pub path: String,
    pub stats: DriveStats,
}

impl<'de> Deserialize<'de> for Drive {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(DriveVisitor)
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DriveStats {
    pub available_bytes: usize,
    pub total_bytes: usize,
    // EventstoreDB v24.2 has the value as an string representing the percent like 30%
    // v24.6 has it as integer value like 30. Here we handle both.
    #[serde(deserialize_with = "percent_or_integer")]
    pub usage: usize,
    pub used_bytes: usize,
}

struct DriveVisitor;

impl<'de> Visitor<'de> for DriveVisitor {
    type Value = Drive;

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "DriveStats object")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, <A as MapAccess<'de>>::Error>
    where
        A: MapAccess<'de>,
    {
        if let Some(key) = map.next_key()? {
            return Ok(Drive {
                path: key,
                stats: map.next_value()?,
            });
        }

        Err(serde::de::Error::missing_field("<Drive path>"))
    }
}

// Can be either an integer or a string like 30%
fn percent_or_integer<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
    D: Deserializer<'de>,
{
    struct PercentOrInteger;
    static PERCENT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\d+)%").unwrap());

    impl<'de> Visitor<'de> for PercentOrInteger {
        type Value = usize;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("string or map")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if let Some(caps) = PERCENT_REGEX.captures(value) {
                caps[1].parse::<usize>().map_err(|err| {
                    Error::custom(format!("could not parse percent value into usize: {}", err))
                })
            } else {
                Err(de::Error::invalid_value(
                    Unexpected::Str(value),
                    &"string did not contain a percent value like 30%",
                ))
            }
        }

        fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            usize::try_from(v).map_err(Error::custom)
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            usize::try_from(v).map_err(Error::custom)
        }
    }

    deserializer.deserialize_any(PercentOrInteger)
}