proc_sys_parser 0.1.22

This crate provides routines for parsing linux /proc files into Rust structs. There are multiple other crates doing this, but these either do not choose to process the statistics in way to make them directly usable, or generalize the statistics and loose the detail.
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
/*!
Read data from `/proc/pressure/cpu`, `/proc/pressure/io`, `/proc/pressure/memory` into the struct [`ProcPressure`].

The processor of `/proc/pressure` takes the values from the files, and puts them in the struct [`ProcPressure`].
The files are cpu, io and memory as topics for pressure information.
Inside the files, these are divided between some and full, meaning some tasks were affected or full, meaning all tasks were.
For both some and full, the fields are a percentage of ? for 10 seconds, 60 seconds and 300 seconds, and total time spent
waiting in microseconds. (the linux kernel is not consistent with time units, having jiffies, nanoseconds and milliseconds as units).

Documentation: <https://docs.kernel.org/accounting/psi.html>

Here is an example obtaining the data from `/proc/pressure`:
```no_run
use proc_sys_parser::pressure;

let proc_pressure = pressure::read();

println!("{:#?}", proc_pressure);
```
Example output:
```text
ProcPressure {
            psi: Some(
                Psi {
                    cpu_some_avg10: 1.0,
                    cpu_some_avg60: 2.0,
                    cpu_some_avg300: 3.0,
                    cpu_some_total: 373300065,
                    cpu_full_avg10: Some( 4.0 ),
                    cpu_full_avg60: Some( 5.0 ),
                    cpu_full_avg300: Some( 6.0 ),
                    cpu_full_total: Some( 0 ),
                    io_some_avg10: 7.0,
                    io_some_avg60: 8.0,
                    io_some_avg300: 9.0,
                    io_some_total: 55345502,
                    io_full_avg10: 10.0,
                    io_full_avg60: 11.0,
                    io_full_avg300: 12.0,
                    io_full_total: 53895423,
                    memory_some_avg10: 13.0,
                    memory_some_avg60: 14.0,
                    memory_some_avg300: 15.0,
                    memory_some_total: 5425111,
                    memory_full_avg10: 16.0,
                    memory_full_avg60: 17.0,
                    memory_full_avg300: 18.0,
                    memory_full_total: 5390695,
                }
            )
        }
```
(edited for readability)

If you want to change the default path that is read for [`ProcPressure`], which is `/proc`, use:
```no_run
use proc_sys_parser::{pressure, pressure::Builder};

let proc_pressure = Builder::new().path("/myproc").read();
```

If the `/proc/pressure` entry is not available because it didn't exist in that linux version, or because it's not enabled
The ProcPressure.psi entry is set to None.

*/
use std::fs::read_to_string;
use crate::ProcSysParserError;
use log::warn;


/// Struct for holding `/proc/pressure` statistics
#[derive(Debug, PartialEq, Default)]
pub struct ProcPressure {
    /// psi is None if no /proc/pressure is found.
    pub psi: Option<Psi>,
}
///
#[derive(Debug, PartialEq, Default)]
pub struct Psi {
    pub cpu_some_avg10: f64,
    pub cpu_some_avg60: f64,
    pub cpu_some_avg300: f64,
    pub cpu_some_total: u64,
    pub cpu_full_avg10: Option<f64>,
    pub cpu_full_avg60: Option<f64>,
    pub cpu_full_avg300: Option<f64>,
    pub cpu_full_total: Option<u64>,
    pub io_some_avg10: f64,
    pub io_some_avg60: f64,
    pub io_some_avg300: f64,
    pub io_some_total: u64,
    pub io_full_avg10: f64,
    pub io_full_avg60: f64,
    pub io_full_avg300: f64,
    pub io_full_total: u64,
    pub memory_some_avg10: f64,
    pub memory_some_avg60: f64,
    pub memory_some_avg300: f64,
    pub memory_some_total: u64,
    pub memory_full_avg10: f64,
    pub memory_full_avg60: f64,
    pub memory_full_avg300: f64,
    pub memory_full_total: u64,
}

impl Psi {
    pub fn new() -> Psi {
        Psi::default() 
    }
}

/// Builder pattern for [`ProcPressure`]
#[derive(Default)]
pub struct Builder {
    pub proc_path : String,
    pub proc_file : String,
}

impl Builder {
    pub fn new() -> Builder {
        Builder { 
            proc_path: "/proc".to_string(),
            proc_file: "pressure".to_string(),
        }
    }

    pub fn path(mut self, proc_path: &str) -> Builder {
        self.proc_path = proc_path.to_string();
        self
    }
    pub fn file(mut self, proc_file: &str) -> Builder {
        self.proc_file = proc_file.to_string();
        self
    }
    pub fn read(self) -> Result<ProcPressure, ProcSysParserError> {
        ProcPressure::read_proc_pressure(format!("{}/pressure", &self.proc_path).as_str())
    }
}

/// The main function for building a [`ProcPressure`] struct with current data.
/// This uses the Builder pattern, which allows settings such as the filename to specified.
pub fn read() -> Result<ProcPressure, ProcSysParserError> {
   Builder::new().read()
}

impl ProcPressure {
    pub fn new() -> ProcPressure {
        ProcPressure {
            psi: None,
        }
    }
    pub fn read_proc_pressure(proc_pressure_path: &str) -> Result<ProcPressure, ProcSysParserError> {
        let mut proc_pressure = ProcPressure::new();

        let mut psi = Psi::new();

        for psi_target in ["cpu", "io", "memory"] {
            if ProcPressure::parse_pressure_entity(psi_target, proc_pressure_path, &mut psi)?.is_none() {
                return Ok(proc_pressure);
            }
        }
        proc_pressure.psi = Some(psi);

        Ok(proc_pressure)
    }
    fn parse_pressure_entity(file: &str, proc_pressure_path: &str, psi: &mut Psi) -> Result<Option<usize>, ProcSysParserError> {
        match read_to_string(format!("{}/{}", &proc_pressure_path, file)) {
            Ok(psi_contents)  => {
                for line in psi_contents.lines() {
                    match line.split_whitespace().next() {
                        Some("some") => {
                            match file {
                                "cpu" => {
                                    psi.cpu_some_avg10 = line.split_whitespace().nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg10".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg10 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.cpu_some_avg60 = line.split_whitespace().nth(2)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg60".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg60 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.cpu_some_avg300 = line.split_whitespace().nth(3)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg300".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg300 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.cpu_some_total = line.split_whitespace().nth(4)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_total".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_total after split =".to_string() })?
                                        .parse::<u64>().map_err(ProcSysParserError::ParseToIntegerError)?;
                                },
                                "io" => {
                                    psi.io_some_avg10 = line.split_whitespace().nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg10".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg10 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.io_some_avg60 = line.split_whitespace().nth(2)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg60".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg60 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.io_some_avg300 = line.split_whitespace().nth(3)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg300".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg300 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.io_some_total = line.split_whitespace().nth(4)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_total".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_total after split =".to_string() })?
                                        .parse::<u64>().map_err(ProcSysParserError::ParseToIntegerError)?;
                                },
                                "memory" => {
                                    psi.memory_some_avg10 = line.split_whitespace().nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg10".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg10 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.memory_some_avg60 = line.split_whitespace().nth(2)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg60".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg60 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.memory_some_avg300 = line.split_whitespace().nth(3)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg300".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg300 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.memory_some_total = line.split_whitespace().nth(4)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_total".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_total after split =".to_string() })?
                                        .parse::<u64>().map_err(ProcSysParserError::ParseToIntegerError)?;
                                },
                                &_ => warn!("Unknown entry in some: {}, {}", file, line),
                            }
                        },
                        Some("full") => {
                            match file {
                                "cpu" => {
                                    psi.cpu_full_avg10 = Some(line.split_whitespace().nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg10".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg10 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?);
                                    psi.cpu_full_avg60 = Some(line.split_whitespace().nth(2)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg60".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg60 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?);
                                    psi.cpu_full_avg300 = Some(line.split_whitespace().nth(3)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg300".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_avg300 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?);
                                    psi.cpu_full_total = Some(line.split_whitespace().nth(4)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_total".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure cpu_some_total after split =".to_string() })?
                                        .parse::<u64>().map_err(ProcSysParserError::ParseToIntegerError)?);
                                },
                                "io" => {
                                    psi.io_full_avg10 = line.split_whitespace().nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg10".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg10 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.io_full_avg60 = line.split_whitespace().nth(2)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg60".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg60 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.io_full_avg300 = line.split_whitespace().nth(3)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg300".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_avg300 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.io_full_total = line.split_whitespace().nth(4)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_total".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure io_some_total after split =".to_string() })?
                                        .parse::<u64>().map_err(ProcSysParserError::ParseToIntegerError)?;
                                },
                                "memory" => {
                                    psi.memory_full_avg10 = line.split_whitespace().nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg10".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg10 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.memory_full_avg60 = line.split_whitespace().nth(2)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg60".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg60 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.memory_full_avg300 = line.split_whitespace().nth(3)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg300".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_avg300 after split =".to_string() })?
                                        .parse::<f64>().map_err(ProcSysParserError::ParseToFloatError)?;
                                    psi.memory_full_total = line.split_whitespace().nth(4)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_total".to_string() })?
                                        .split('=').nth(1)
                                        .ok_or(ProcSysParserError::IteratorItemError {item: "pressure memory_some_total after split =".to_string() })?
                                        .parse::<u64>().map_err(ProcSysParserError::ParseToIntegerError)?;
                                },
                                &_ => warn!("Unknown entry in full: {}, {}", file, line),
                            }
                        },
                        Some(&_) => warn!("Unknown entry found: {}", line),
                        None => {},
                    }
                }
                Ok(Some(1))
            },
            Err(_) => {
                Ok(None)
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs::{write, remove_dir_all, create_dir_all};
    use rand::{thread_rng, Rng};
    use rand::distributions::Alphanumeric;
    use super::*;

    #[test]
    fn create_proc_pressure_directory_and_files_and_read() {
        let proc_pressure_cpu = "some avg10=1.00 avg60=2.00 avg300=3.00 total=373300065
full avg10=4.00 avg60=5.00 avg300=6.00 total=0
";
        let proc_pressure_io = "some avg10=7.00 avg60=8.00 avg300=9.00 total=55345502
full avg10=10.00 avg60=11.00 avg300=12.00 total=53895423
";
        let proc_pressure_memory = "some avg10=13.00 avg60=14.00 avg300=15.00 total=5425111
full avg10=16.00 avg60=17.00 avg300=18.00 total=5390695
";

        let directory_suffix: String = thread_rng().sample_iter(&Alphanumeric).take(8).map(char::from).collect();
        let test_path = format!("/tmp/test.{}", directory_suffix);
        create_dir_all(format!("{}/pressure", test_path)).expect("Error creating mock directory.");

        write(format!("{}/pressure/cpu", test_path), proc_pressure_cpu).expect(format!("Error writing to {}/pressure/cpu", test_path).as_str());
        write(format!("{}/pressure/io", test_path), proc_pressure_io).expect(format!("Error writing to {}/pressure/io", test_path).as_str());
        write(format!("{}/pressure/memory", test_path), proc_pressure_memory).expect(format!("Error writing to {}/pressure/memory", test_path).as_str());

        let result = Builder::new().path(&test_path).read().unwrap();

        remove_dir_all(test_path).unwrap();

        assert_eq!(result, ProcPressure {
            psi: Some(
                Psi {
                    cpu_some_avg10: 1.0,
                    cpu_some_avg60: 2.0,
                    cpu_some_avg300: 3.0,
                    cpu_some_total: 373300065,
                    cpu_full_avg10: Some(
                        4.0,
                    ),
                    cpu_full_avg60: Some(
                        5.0,
                    ),
                    cpu_full_avg300: Some(
                        6.0,
                    ),
                    cpu_full_total: Some(
                        0,
                    ),
                    io_some_avg10: 7.0,
                    io_some_avg60: 8.0,
                    io_some_avg300: 9.0,
                    io_some_total: 55345502,
                    io_full_avg10: 10.0,
                    io_full_avg60: 11.0,
                    io_full_avg300: 12.0,
                    io_full_total: 53895423,
                    memory_some_avg10: 13.0,
                    memory_some_avg60: 14.0,
                    memory_some_avg300: 15.0,
                    memory_some_total: 5425111,
                    memory_full_avg10: 16.0,
                    memory_full_avg60: 17.0,
                    memory_full_avg300: 18.0,
                    memory_full_total: 5390695,
                },
            ),
        });
    }
    #[test]
    fn do_not_create_proc_pressure_directory_for_nonexistent_cases_and_read() {
        let directory_suffix: String = thread_rng().sample_iter(&Alphanumeric).take(8).map(char::from).collect();
        let test_path = format!("/tmp/test.{}", directory_suffix);
        create_dir_all(format!("{}", test_path)).expect("Error creating mock directory.");

        let result = Builder::new().path(&test_path).read().unwrap();
        remove_dir_all(test_path).unwrap();

        assert_eq!(result, ProcPressure { psi: None });
    }
}