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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
use crate::util::{read_to_string_mut, blkdev_sector_size};
use crate::unit::DataSize;
use std::path::Path;
use std::{fs, io};
use std::convert::TryInto;
use byte_parser::{StrParser, ParseIterator, parse_iter};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Partitions {
raw: String
}
impl Partitions {
fn path() -> &'static Path {
Path::new("/proc/partitions")
}
#[cfg(test)]
fn from_string(raw: String) -> Self {
Self {raw}
}
pub fn read() -> io::Result<Self> {
Ok(Self {
raw: fs::read_to_string(Self::path())?
})
}
pub fn reload(&mut self) -> io::Result<()> {
read_to_string_mut(Self::path(), &mut self.raw)
}
pub fn entries<'a>(&'a self) -> impl Iterator<Item=PartitionEntry<'a>> {
self.raw.trim()
.split('\n')
.skip(2)
.map(PartitionEntry::from_str)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartitionEntry<'a> {
raw: &'a str
}
impl<'a> PartitionEntry<'a> {
fn from_str(raw: &'a str) -> Self {
Self {raw}
}
pub fn values(&self) -> impl Iterator<Item=&'a str> {
self.raw.split(' ')
.map(str::trim)
.filter(|s| !s.is_empty())
}
pub fn major(&self) -> Option<usize> {
self.values().nth(0)?
.parse().ok()
}
pub fn minor(&self) -> Option<usize> {
self.values().nth(1)?
.parse().ok()
}
pub fn blocks(&self) -> Option<usize> {
self.values().nth(2)?
.parse().ok()
}
pub fn name(&self) -> Option<&'a str> {
self.values().nth(3)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MountPoints {
raw: String
}
impl MountPoints {
fn path() -> &'static Path {
Path::new("/proc/self/mountinfo")
}
#[cfg(test)]
fn from_string(raw: String) -> Self {
Self {raw}
}
pub fn read() -> io::Result<Self> {
Ok(Self {
raw: fs::read_to_string(Self::path())?
})
}
pub fn reload(&mut self) -> io::Result<()> {
read_to_string_mut(Self::path(), &mut self.raw)
}
pub fn points<'a>(&'a self) -> impl Iterator<Item=MountPoint<'a>> {
self.raw.trim()
.split('\n')
.map(MountPoint::from_str)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MountPoint<'a> {
raw: &'a str
}
impl<'a> MountPoint<'a> {
fn from_str(raw: &'a str) -> Self {
Self {raw}
}
#[inline]
pub fn values(&self) -> impl Iterator<Item=&'a str> {
self.raw.split(' ')
}
pub fn mount_id(&self) -> Option<usize> {
self.values().nth(0)?
.parse().ok()
}
pub fn parent_id(&self) -> Option<usize> {
self.values().nth(1)?
.parse().ok()
}
#[inline]
pub fn major_minor(&self) -> Option<&'a str> {
self.values().nth(2)
}
pub fn major(&self) -> Option<usize> {
self.major_minor()?
.split(':')
.nth(0)?
.parse().ok()
}
pub fn minor(&self) -> Option<usize> {
self.major_minor()?
.split(':')
.nth(1)?
.parse().ok()
}
pub fn root(&self) -> Option<&'a str> {
self.values().nth(3)
}
pub fn mount_point(&self) -> Option<&'a str> {
self.values().nth(4)
}
pub fn mount_options(&self) -> Option<&'a str> {
self.values().nth(5)
}
pub fn optional_fields(&self) -> impl Iterator<Item=(&'a str, Option<&'a str>)> {
self.values().skip(6)
.take_while(|&i| i != "-")
.map(|opt| {
let mut iters = opt.split(':');
(
iters.next().unwrap(),
iters.next()
)
})
}
fn after_separator(&self) -> impl Iterator<Item=&'a str> {
self.values().skip(5)
.skip_while(|&i| i != "-")
.skip(1)
}
pub fn filesystem_type(&self) -> Option<&'a str> {
self.after_separator().nth(0)
}
pub fn mount_source(&self) -> Option<&'a str> {
self.after_separator().nth(1)
}
pub fn super_options(&self) -> Option<&'a str> {
self.after_separator().nth(2)
}
pub fn stats(&self) -> io::Result<FsStat> {
FsStat::read(self.mount_point().unwrap_or(""))
}
}
#[derive(Clone)]
pub struct FsStat {
raw: libc::statfs
}
impl FsStat {
pub fn read(path: impl AsRef<Path>) -> io::Result<Self> {
crate::util::statfs(path)
.map(|raw| Self { raw })
}
pub fn has_blocks(&self) -> bool {
self.total_blocks()
.map(|b| b > 0)
.unwrap_or(false)
}
pub fn block_size(&self) -> Option<usize> {
self.raw.f_bsize.try_into().ok()
}
pub fn total_blocks(&self) -> Option<usize> {
self.raw.f_blocks.try_into().ok()
}
pub fn free_blocks(&self) -> Option<usize> {
self.raw.f_bfree.try_into().ok()
}
pub fn available_blocks(&self) -> Option<usize> {
self.raw.f_bavail.try_into().ok()
}
pub fn used_blocks(&self) -> Option<usize> {
Some(self.total_blocks()? - self.free_blocks()?)
}
pub fn total(&self) -> Option<DataSize> {
DataSize::from_size_bytes(self.total_blocks()? * self.block_size()?)
}
pub fn free(&self) -> Option<DataSize> {
DataSize::from_size_bytes(self.free_blocks()? * self.block_size()?)
}
pub fn available(&self) -> Option<DataSize> {
DataSize::from_size_bytes(self.available_blocks()? * self.block_size()?)
}
pub fn used(&self) -> Option<DataSize> {
DataSize::from_size_bytes(self.used_blocks()? * self.block_size()?)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Raids {
raw: String
}
impl Raids {
fn path() -> &'static Path {
Path::new("/proc/mdstat")
}
#[cfg(test)]
fn from_string(raw: String) -> Self {
Self {raw}
}
pub fn read() -> io::Result<Self> {
Ok(Self {
raw: fs::read_to_string(Self::path())?
})
}
pub fn reload(&mut self) -> io::Result<()> {
read_to_string_mut(Self::path(), &mut self.raw)
}
pub fn raids(&self) -> impl Iterator<Item=Raid<'_>> {
let mut first_line = false;
parse_iter(
StrParser::new(self.raw.trim()),
move |parser| {
if !first_line {
parser.consume_while_byte_fn(|&b| b != b'\n');
parser.advance();
first_line = true;
}
parser.peek()?;
let key = parser.record()
.while_byte_fn(|&b| b != b':')
.consume_to_str()
.trim();
if key == "unused devices" {
return None
}
parser.advance();
let mut parser = parser.record();
let mut one = false;
loop {
if one && matches!(parser.peek(), Some(b'\n')) {
let s = parser.to_str().trim();
parser.advance();
return Some(Raid::from_str(key, s))
}
if one {
one = false;
continue
}
match parser.next() {
Some(b'\n') => one = true,
None => {
return Some(Raid::from_str(key, parser.to_str().trim()))
},
_ => {}
}
}
}
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Raid<'a> {
name: &'a str,
raw: &'a str
}
impl<'a> Raid<'a> {
fn from_str(name: &'a str, raw: &'a str) -> Self {
Self {name, raw}
}
#[inline]
pub fn values(&self) -> impl Iterator<Item=impl Iterator<Item=&'a str>> {
self.raw.split('\n')
.map(str::trim)
.map(|l| l.split(' '))
}
pub fn name(&self) -> &'a str {
self.name
}
pub fn state(&self) -> Option<&'a str> {
self.values()
.nth(0)?
.nth(0)
}
fn line(&self, line: usize) -> impl Iterator<Item=&'a str> {
let mut iter = self.values().nth(line);
std::iter::from_fn(move || iter.as_mut()?.next())
}
pub fn kind(&self) -> Option<&'a str> {
self.line(0).nth(1)
}
pub fn devices(&self) -> impl Iterator<Item=(usize, &'a str)> {
self.line(0)
.skip(2)
.filter_map(|dev| {
let mut split = dev.split(&['[', ']'][..]);
let name = split.next()?;
Some((
split.next()?.parse().ok()?,
name
))
})
}
pub fn usable_blocks(&self) -> Option<usize> {
self.line(1)
.nth(0)?
.parse().ok()
}
pub fn used_devices(&self) -> Option<usize> {
self.line(1)
.find(|l| l.starts_with('['))?
.split('/')
.nth(0)?
.strip_prefix('[')?
.parse().ok()
}
pub fn ideal_devices(&self) -> Option<usize> {
self.line(1)
.find(|l| l.starts_with('['))?
.split('/')
.nth(1)?
.strip_suffix(']')?
.parse().ok()
}
pub fn progress(&self) -> Option<&'a str> {
let l = self.raw.split('\n')
.nth(2)?
.trim();
l.starts_with('[')
.then(|| l)
}
pub fn stats(&self) -> io::Result<FsStat> {
FsStat::read(format!("/dev/{}", self.name()))
}
}
pub fn sector_size(path: impl AsRef<Path>) -> io::Result<u64> {
blkdev_sector_size(fs::File::open(path)?)
}
#[cfg(test)]
mod tests {
use super::*;
fn partitions() -> Partitions {
Partitions::from_string("\
major minor #blocks name
7 0 142152 loop0
7 1 101528 loop1
259 0 500107608 nvme0n1
259 1 510976 nvme0n1p1\n\
".into())
}
fn cmp_entry(major: usize, minor: usize, blocks: usize, name: &str, e: &PartitionEntry<'_>) {
assert_eq!(e.major().unwrap(), major);
assert_eq!(e.minor().unwrap(), minor);
assert_eq!(e.blocks().unwrap(), blocks);
assert_eq!(e.name().unwrap(), name);
}
#[test]
fn all_partitions() {
let part = partitions();
let mut e = part.entries();
println!("e: {:?}", part.entries().collect::<Vec<_>>());
cmp_entry(7, 0, 142152, "loop0", &e.next().unwrap());
cmp_entry(7, 1, 101528, "loop1", &e.next().unwrap());
cmp_entry(259, 0, 500107608, "nvme0n1", &e.next().unwrap());
cmp_entry(259, 1, 510976, "nvme0n1p1", &e.next().unwrap());
assert!(e.next().is_none());
}
fn mount_points() -> MountPoints {
MountPoints::from_string("\
26 29 0:5 / /dev rw,nosuid,noexec,relatime shared:2 - devtmpfs udev rw,size=8123832k,nr_inodes=2030958,mode=755
27 26 0:24 / /dev/pts rw,nosuid,noexec,relatime shared:3 - devpts devpts rw,gid=5,mode=620,ptmxmode=000
35 33 0:30 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime shared:11 other - cgroup cgroup rw,xattr,name=systemd
2509 28 0:25 /snapd/ns /run/snapd/ns rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,size=1631264k,mode=755
2893 2509 0:4 mnt:[4026532961] /run/snapd/ns/snap-store.mnt rw - nsfs nsfs rw\n\
".into())
}
fn cmp_point(
mount_id: usize,
parent_id: usize,
major_minor: &str,
root: &str,
mount_point: &str,
mount_options: &str,
optional_fields: &[(&str, Option<&str>)],
filesystem_type: &str,
mount_source: &str,
super_options: &str,
point: &MountPoint<'_>
) {
assert_eq!(point.mount_id().unwrap(), mount_id);
assert_eq!(point.parent_id().unwrap(), parent_id);
assert_eq!(point.major_minor().unwrap(), major_minor);
assert_eq!(point.root().unwrap(), root);
assert_eq!(point.mount_point().unwrap(), mount_point);
assert_eq!(point.mount_options().unwrap(), mount_options);
assert_eq!(point.optional_fields().collect::<Vec<_>>(), optional_fields);
assert_eq!(point.filesystem_type().unwrap(), filesystem_type);
assert_eq!(point.mount_source().unwrap(), mount_source);
assert_eq!(point.super_options().unwrap(), super_options);
}
#[test]
fn all_mount_points() {
let mt = mount_points();
let mut mt = mt.points();
cmp_point(
26, 29, "0:5", "/", "/dev", "rw,nosuid,noexec,relatime",
&[("shared", Some("2"))], "devtmpfs", "udev",
"rw,size=8123832k,nr_inodes=2030958,mode=755",
&mt.next().unwrap()
);
cmp_point(
27, 26, "0:24", "/", "/dev/pts", "rw,nosuid,noexec,relatime",
&[("shared", Some("3"))], "devpts", "devpts",
"rw,gid=5,mode=620,ptmxmode=000",
&mt.next().unwrap()
);
cmp_point(
35, 33, "0:30", "/", "/sys/fs/cgroup/systemd", "rw,nosuid,nodev,noexec,relatime",
&[("shared", Some("11")), ("other", None)], "cgroup", "cgroup", "rw,xattr,name=systemd",
&mt.next().unwrap()
);
cmp_point(
2509, 28, "0:25", "/snapd/ns", "/run/snapd/ns", "rw,nosuid,nodev,noexec,relatime",
&[], "tmpfs", "tmpfs", "rw,size=1631264k,mode=755",
&mt.next().unwrap()
);
cmp_point(
2893, 2509, "0:4", "mnt:[4026532961]", "/run/snapd/ns/snap-store.mnt", "rw",
&[], "nsfs", "nsfs", "rw",
&mt.next().unwrap()
);
}
#[test]
fn raid_case_1() {
let raids = Raids::from_string("\
Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10]
md10 : active raid1 sdd[0] sdc[1]
3906886464 blocks super 1.2 [2/2] [UU]
bitmap: 0/30 pages [0KB], 65536KB chunk
md0 : active raid1 sdb[1] sda[0]
499975488 blocks super 1.2 [2/2] [UU]
bitmap: 3/4 pages [12KB], 65536KB chunk
unused devices: <none>\n".into());
assert_eq!(raids.raids().count(), 2);
let first = raids.raids().next().unwrap();
assert_eq!(first.name(), "md10");
assert_eq!(first.used_devices().unwrap(), 2);
assert_eq!(first.ideal_devices().unwrap(), 2);
assert!(first.progress().is_none());
assert_eq!(first.devices().count(), first.used_devices().unwrap());
}
#[test]
fn raid_case_2() {
let raids = Raids::from_string("\
Personalities : [raid1] [raid6] [raid5] [raid4]
md127 : active raid5 sdh1[6] sdg1[4] sdf1[3] sde1[2] sdd1[1] sdc1[0]
1464725760 blocks level 5, 64k chunk, algorithm 2 [6/5] [UUUUU_]
[==>..................] recovery = 12.6% (37043392/292945152) finish=127.5min speed=33440K/sec
unused devices: <none>\n".into());
assert_eq!(raids.raids().count(), 1);
let first = raids.raids().next().unwrap();
let comp_dev: Vec<_> = first.devices().collect();
assert_eq!(comp_dev, [(6, "sdh1"), (4, "sdg1"), (3, "sdf1"), (2, "sde1"), (1, "sdd1"), (0, "sdc1")]);
assert_eq!(first.kind().unwrap(), "raid5");
assert_eq!(first.usable_blocks().unwrap(), 1464725760);
assert_eq!(first.used_devices().unwrap(), 6);
assert_eq!(first.ideal_devices().unwrap(), 5);
assert_eq!(first.progress().unwrap(), "[==>..................] recovery = 12.6% (37043392/292945152) finish=127.5min speed=33440K/sec");
assert_eq!(first.devices().count(), first.used_devices().unwrap());
}
#[test]
fn raid_case_3() {
let raids = Raids::from_string("\
Personalities : [linear] [raid0] [raid1] [raid5] [raid4] [raid6]
md0 : active raid6 sdf1[0] sde1[1] sdd1[2] sdc1[3] sdb1[4] sda1[5] hdb1[6]
1225557760 blocks level 6, 256k chunk, algorithm 2 [7/7] [UUUUUUU]
bitmap: 0/234 pages [0KB], 512KB chunk
unused devices: <none>\n".into());
assert_eq!(raids.raids().count(), 1);
let first = raids.raids().next().unwrap();
assert_eq!(first.devices().count(), first.used_devices().unwrap());
}
}