procsys 0.7.0

Rust library to retrieve system, kernel, and process metrics from the pseudo-filesystems /proc and /sys
Documentation
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use serde::Serialize;

use crate::{
    error::{CollectResult, MetricError},
    utils,
};

enum CpuInfoInfo {
    Processor,
    VendorID,
    CpuFamily,
    Model,
    ModelName,
    Stepping,
    Microcode,
    CpuMhz,
    CacheSizeBytes,
    PhysicalID,
    Siblings,
    CoreID,
    CpuCores,
    ApicID,
    InitialApicID,
    Fpu,
    FpuException,
    CpuIDLevel,
    Wp,
    Flags,
    VmxFlags,
    Bugs,
    BogoMips,
    ClflushSize,
    CacheAlignment,
    AddressSize,
    PowerManagement,
    Unknown,
}

impl CpuInfoInfo {
    fn from(name: &str) -> CpuInfoInfo {
        match name {
            "processor" => CpuInfoInfo::Processor,
            "vendor_id" => CpuInfoInfo::VendorID,
            "cpu family" => CpuInfoInfo::CpuFamily,
            "model" => CpuInfoInfo::Model,
            "model name" => CpuInfoInfo::ModelName,
            "stepping" => CpuInfoInfo::Stepping,
            "microcode" => CpuInfoInfo::Microcode,
            "cpu MHz" => CpuInfoInfo::CpuMhz,
            "cache size" => CpuInfoInfo::CacheSizeBytes,
            "physical id" => CpuInfoInfo::PhysicalID,
            "siblings" => CpuInfoInfo::Siblings,
            "core id" => CpuInfoInfo::CoreID,
            "cpu cores" => CpuInfoInfo::CpuCores,
            "apicid" => CpuInfoInfo::ApicID,
            "initial apicid" => CpuInfoInfo::InitialApicID,
            "fpu" => CpuInfoInfo::Fpu,
            "fpu_exception" => CpuInfoInfo::FpuException,
            "cpuid level" => CpuInfoInfo::CpuIDLevel,
            "wp" => CpuInfoInfo::Wp,
            "flags" => CpuInfoInfo::Flags,
            "vmx flags" => CpuInfoInfo::VmxFlags,
            "bugs" => CpuInfoInfo::Bugs,
            "bogomips" => CpuInfoInfo::BogoMips,
            "clflush size" => CpuInfoInfo::ClflushSize,
            "cache_alignment" => CpuInfoInfo::CacheAlignment,
            "address sizes" => CpuInfoInfo::AddressSize,
            "power management" => CpuInfoInfo::PowerManagement,
            _ => CpuInfoInfo::Unknown,
        }
    }
}

/// CpuInfo contains general information about a system CPU found in /proc/cpuinfo
#[derive(Debug, Serialize, Clone, Default)]
pub struct CpuInfo {
    pub processor: u32,
    pub vendor_id: String,
    pub cpu_family: u32,
    pub model: u32,
    pub model_name: String,
    pub stepping: u32,
    pub microcode: String,
    pub cpu_mhz: f64,
    pub cache_size_bytes: u64,
    pub physical_id: u32,
    pub siblings: u32,
    pub core_id: u32,
    pub cpu_cores: u32,
    pub apic_id: u32,
    pub initial_apic_id: u32,
    pub fpu: String,
    pub fpu_exception: String,
    pub cpu_id_level: u32,
    pub wp: String,
    pub flags: Vec<String>,
    pub vmx_flags: Vec<String>,
    pub bugs: Vec<String>,
    pub bogomips: f64,
    pub clflush_size: u32,
    pub cache_alignment: u32,
    pub address_sizes: String,
    pub power_management: String,
}

impl CpuInfo {
    fn new() -> Self {
        Default::default()
    }
}

/// collects information about current system CPUs
/// # Example
/// ```
/// use procsys::cpuinfo;
///
/// let sys_cpuinfo = cpuinfo::collect().expect("cpu information");
/// let json_output = serde_json::to_string_pretty(&sys_cpuinfo).unwrap();
/// println!("{}", json_output);
///
/// ```
pub fn collect() -> CollectResult<Vec<CpuInfo>> {
    collect_from("/proc/cpuinfo")
}

fn collect_from(filename: &str) -> CollectResult<Vec<CpuInfo>> {
    let mut sys_cpuinfo: Vec<CpuInfo> = Vec::new();

    let mut info_index = 0;
    for line in utils::read_file_lines(filename)? {
        if line.trim().is_empty() {
            continue;
        }

        let item_fields: Vec<&str> = line.trim().split(':').filter(|s| !s.is_empty()).collect();

        let metric = item_fields[0].trim();
        let mut metric_value = None;

        if item_fields.len() == 2 {
            metric_value = Some(item_fields[1].trim().to_string());
        }

        if metric_value.is_none() {
            continue;
        }

        match CpuInfoInfo::from(metric) {
            CpuInfoInfo::Processor => {
                if !sys_cpuinfo.is_empty() {
                    info_index += 1;
                }

                let processor = metric_value
                    .unwrap_or_default()
                    .parse::<u32>()
                    .unwrap_or_default();

                let mut cpuinfo = CpuInfo::new();
                cpuinfo.processor = processor;
                sys_cpuinfo.push(cpuinfo);
            }
            CpuInfoInfo::VendorID => {
                sys_cpuinfo[info_index].vendor_id = metric_value.unwrap_or_default()
            }
            CpuInfoInfo::CpuFamily => {
                sys_cpuinfo[info_index].cpu_family =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError("cpu family".to_string(), err));
                        }
                    };
            }
            CpuInfoInfo::Model => {
                sys_cpuinfo[info_index].model =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError("cpu model".to_string(), err));
                        }
                    };
            }
            CpuInfoInfo::ModelName => {
                sys_cpuinfo[info_index].model_name = metric_value.unwrap_or_default()
            }
            CpuInfoInfo::Stepping => {
                sys_cpuinfo[info_index].stepping = match metric_value
                    .unwrap_or_default()
                    .parse::<u32>()
                {
                    Ok(c) => c,
                    Err(err) => {
                        return Err(MetricError::ParseIntError("cpu stepping".to_string(), err));
                    }
                };
            }
            CpuInfoInfo::Microcode => {
                sys_cpuinfo[info_index].microcode = metric_value.unwrap_or_default()
            }
            CpuInfoInfo::CpuMhz => {
                sys_cpuinfo[info_index].cpu_mhz =
                    match metric_value.unwrap_or_default().parse::<f64>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseFloatError("cpu mhz".to_string(), err));
                        }
                    };
            }
            CpuInfoInfo::CacheSizeBytes => {
                let value = metric_value.unwrap_or_default();
                let value_fields: Vec<&str> =
                    value.trim().split(' ').filter(|s| !s.is_empty()).collect();

                let item_value = value_fields[0].parse::<u64>().unwrap_or_default();
                let mut item_unit = "B";
                if value_fields.len() == 2 {
                    item_unit = value_fields[1];
                }

                sys_cpuinfo[info_index].cache_size_bytes =
                    utils::convert_to_bytes(item_value, item_unit)?.unwrap();
            }
            CpuInfoInfo::PhysicalID => {
                sys_cpuinfo[info_index].physical_id =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError(
                                "cpu physical id".to_string(),
                                err,
                            ));
                        }
                    };
            }
            CpuInfoInfo::Siblings => {
                sys_cpuinfo[info_index].siblings = match metric_value
                    .unwrap_or_default()
                    .parse::<u32>()
                {
                    Ok(c) => c,
                    Err(err) => {
                        return Err(MetricError::ParseIntError("cpu siblings".to_string(), err));
                    }
                };
            }
            CpuInfoInfo::CoreID => {
                sys_cpuinfo[info_index].core_id =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError("cpu core id".to_string(), err));
                        }
                    };
            }
            CpuInfoInfo::CpuCores => {
                sys_cpuinfo[info_index].cpu_cores =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError("cpu cores".to_string(), err));
                        }
                    };
            }
            CpuInfoInfo::ApicID => {
                sys_cpuinfo[info_index].apic_id =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError("cpu apic id".to_string(), err));
                        }
                    };
            }
            CpuInfoInfo::InitialApicID => {
                sys_cpuinfo[info_index].initial_apic_id =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError(
                                "cpu initial apic id".to_string(),
                                err,
                            ));
                        }
                    };
            }
            CpuInfoInfo::Fpu => sys_cpuinfo[info_index].fpu = metric_value.unwrap_or_default(),
            CpuInfoInfo::FpuException => {
                sys_cpuinfo[info_index].fpu_exception = metric_value.unwrap_or_default();
            }
            CpuInfoInfo::CpuIDLevel => {
                sys_cpuinfo[info_index].cpu_id_level = match metric_value
                    .unwrap_or_default()
                    .parse::<u32>()
                {
                    Ok(c) => c,
                    Err(err) => {
                        return Err(MetricError::ParseIntError("cpu id level".to_string(), err));
                    }
                };
            }
            CpuInfoInfo::Wp => sys_cpuinfo[info_index].wp = metric_value.unwrap_or_default(),
            CpuInfoInfo::Flags => {
                for flag in metric_value.unwrap_or_default().trim().split(' ') {
                    sys_cpuinfo[info_index].flags.push(flag.to_string());
                }
            }
            CpuInfoInfo::VmxFlags => {
                for flag in metric_value.unwrap_or_default().trim().split(' ') {
                    sys_cpuinfo[info_index].vmx_flags.push(flag.to_string());
                }
            }
            CpuInfoInfo::Bugs => {
                for flag in metric_value.unwrap_or_default().trim().split(' ') {
                    sys_cpuinfo[info_index].bugs.push(flag.to_string());
                }
            }
            CpuInfoInfo::BogoMips => {
                sys_cpuinfo[info_index].bogomips =
                    match metric_value.unwrap_or_default().parse::<f64>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseFloatError(
                                "cpu bogomips".to_string(),
                                err,
                            ));
                        }
                    };
            }
            CpuInfoInfo::ClflushSize => {
                sys_cpuinfo[info_index].clflush_size =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError(
                                "cpu clflush size".to_string(),
                                err,
                            ));
                        }
                    };
            }
            CpuInfoInfo::CacheAlignment => {
                sys_cpuinfo[info_index].cache_alignment =
                    match metric_value.unwrap_or_default().parse::<u32>() {
                        Ok(c) => c,
                        Err(err) => {
                            return Err(MetricError::ParseIntError(
                                "cpu cache alignment".to_string(),
                                err,
                            ));
                        }
                    };
            }
            CpuInfoInfo::AddressSize => {
                sys_cpuinfo[info_index].address_sizes = metric_value.unwrap_or_default();
            }
            CpuInfoInfo::PowerManagement => {
                sys_cpuinfo[info_index].power_management = metric_value.unwrap_or_default();
            }
            CpuInfoInfo::Unknown => {}
        }
    }

    Ok(sys_cpuinfo)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cpuinfo() {
        let sys_cpuinfo =
            collect_from("test_data/fixtures/proc/cpuinfo").expect("collecting cpu information");
        assert_eq!(sys_cpuinfo.len(), 2);

        for cpu in sys_cpuinfo {
            match cpu.processor {
                0 => {
                    assert_eq!(cpu.vendor_id, "GenuineIntel");
                    assert_eq!(cpu.cpu_family, 6);
                    assert_eq!(cpu.model, 142);
                    assert_eq!(cpu.model_name, "Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz");
                    assert_eq!(cpu.stepping, 10);
                    assert_eq!(cpu.microcode, "0xb4");
                    assert_eq!(cpu.cpu_mhz, 799.998);
                    assert_eq!(cpu.cache_size_bytes, 8388608);
                    assert_eq!(cpu.physical_id, 0);
                    assert_eq!(cpu.siblings, 8);
                    assert_eq!(cpu.core_id, 0);
                    assert_eq!(cpu.cpu_cores, 4);
                    assert_eq!(cpu.apic_id, 0);
                    assert_eq!(cpu.initial_apic_id, 0);
                    assert_eq!(cpu.fpu, "yes");
                    assert_eq!(cpu.fpu_exception, "yes");
                    assert_eq!(cpu.cpu_id_level, 22);
                    assert_eq!(cpu.wp, "yes");
                    assert!(cpu.vmx_flags.is_empty());
                    assert_eq!(
                        cpu.bugs,
                        [
                            "cpu_meltdown",
                            "spectre_v1",
                            "spectre_v2",
                            "spec_store_bypass",
                            "l1tf",
                            "mds",
                            "swapgs",
                        ]
                    );
                    assert_eq!(cpu.clflush_size, 64);
                    assert_eq!(cpu.cache_alignment, 64);
                    assert_eq!(cpu.address_sizes, "39 bits physical, 48 bits virtual");
                    assert_eq!(cpu.bogomips, 4224.00);
                    assert!(cpu.power_management.is_empty());
                }
                1 => {
                    assert_eq!(cpu.vendor_id, "GenuineIntel");
                    assert_eq!(cpu.cpu_family, 6);
                    assert_eq!(cpu.model, 142);
                    assert_eq!(cpu.model_name, "Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz");
                    assert_eq!(cpu.stepping, 10);
                    assert_eq!(cpu.microcode, "0xb4");
                    assert_eq!(cpu.cpu_mhz, 800.037);
                    assert_eq!(cpu.cache_size_bytes, 8388608);
                    assert_eq!(cpu.physical_id, 0);
                    assert_eq!(cpu.siblings, 8);
                    assert_eq!(cpu.core_id, 1);
                    assert_eq!(cpu.cpu_cores, 4);
                    assert_eq!(cpu.apic_id, 2);
                    assert_eq!(cpu.initial_apic_id, 2);
                    assert_eq!(cpu.fpu, "yes");
                    assert_eq!(cpu.fpu_exception, "yes");
                    assert_eq!(cpu.cpu_id_level, 22);
                    assert_eq!(cpu.wp, "yes");
                    assert!(cpu.vmx_flags.is_empty());
                    assert_eq!(
                        cpu.bugs,
                        [
                            "cpu_meltdown",
                            "spectre_v1",
                            "spectre_v2",
                            "spec_store_bypass",
                            "l1tf",
                            "mds",
                            "swapgs",
                        ]
                    );
                    assert_eq!(cpu.clflush_size, 64);
                    assert_eq!(cpu.cache_alignment, 64);
                    assert_eq!(cpu.address_sizes, "39 bits physical, 48 bits virtual");
                    assert_eq!(cpu.bogomips, 4224.00);
                    assert!(cpu.power_management.is_empty());
                }
                _ => panic!("invalid processor: {}", cpu.processor),
            }
        }
    }
}