controlgroup 0.3.0

Native Rust crate for cgroup operations
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
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
use std::{
    fs::{self, File},
    path::{Path, PathBuf},
};

use crate::{
    parse::parse_01_bool,
    v1::{self, Resources, SubsystemKind},
    Error, ErrorKind, Pid, Result,
};

const NOTIFY_ON_RELEASE: &str = "notify_on_release";
const RELEASE_AGENT: &str = "release_agent";

macro_rules! _gen_doc {
    ($op: literal, $file: expr) => { concat!(
"# Errors

This file is present only in the root cgroup. If you call this method on a non-root cgroup, an error
is returned with kind [`ErrorKind::InvalidOperation`]. On the root cgroup, returns an error if
failed to ", $op, " `", $file, "` file of this cgroup.

[`ErrorKind::InvalidOperation`]: ../enum.ErrorKind.html#variant.InvalidOperation\n\n"
    ) };
}

// NOTE: Keep the example below in sync with `README.md` and `lib.rs`

/// Common operations on a cgroup. All subsystem handlers implement this trait.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> controlgroup::Result<()> {
/// use std::path::PathBuf;
/// use controlgroup::{Pid, v1::{cpu, Cgroup, CgroupPath, SubsystemKind, Resources}};
///
/// // Define and create a new cgroup controlled by the CPU subsystem.
/// let mut cgroup = cpu::Subsystem::new(
///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
/// cgroup.create()?;
///
/// // Attach the self process to the cgroup.
/// let pid = Pid::from(std::process::id());
/// cgroup.add_task(pid)?;
///
/// // Define resource limits and constraints for this cgroup.
/// // Here we just use the default for an example.
/// let resources = Resources::default();
///
/// // Apply the resource limits.
/// cgroup.apply(&resources)?;
///
/// // Low-level file operations are also supported.
/// let stat_file = cgroup.open_file_read("cpu.stat")?;
///
/// // Do something ...
///
/// // Now, remove self process from the cgroup.
/// cgroup.remove_task(pid)?;
///
/// // ... and delete the cgroup.
/// cgroup.delete()?;
///
/// // Note that subsystem handlers does not implement `Drop` and therefore when the
/// // handler is dropped, the cgroup will stay around.
/// # Ok(())
/// # }
/// ```
pub trait Cgroup {
    /// Defines a new cgroup with a path.
    ///
    /// Note that this method does not create a new cgroup. [`create`] method creates the new
    /// directory for the defined cgroup.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    /// ```
    ///
    /// [`create`]: #method.create
    fn new(path: CgroupPath) -> Self;

    /// Returns the subsystem to which this cgroup belongs.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::with_subsystem_name("cpu_memory", PathBuf::from("students/charlie")));
    ///
    /// assert_eq!(cgroup.subsystem(), SubsystemKind::Cpu);
    /// ```
    fn subsystem(&self) -> SubsystemKind;

    /// Returns the absolute path to this cgroup.
    ///
    /// The resulting path is the concatenation of 1) the cgroup mount point `sys/fs/cgroup`, 2) the
    /// directory name for the subsystem of this cgroup, and 3) the cgroup name (e.g.
    /// `students/charlie`).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// assert_eq!(cgroup.path(), PathBuf::from("/sys/fs/cgroup/cpu/students/charlie"));
    /// ```
    fn path(&self) -> PathBuf;

    /// Returns whether this cgroup is the root cgroup of a subsystem.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let root = cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, PathBuf::new()));
    /// assert!(root.is_root());
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    /// assert!(!cgroup.is_root());
    /// ```
    fn is_root(&self) -> bool;

    /// Returns the definition of the root cgroup for the subsystem of this cgroup.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// let root = cgroup.root_cgroup();
    ///
    /// assert!(root.is_root());
    /// assert_eq!(root.path(), PathBuf::from("/sys/fs/cgroup/cpu"));
    /// ```
    fn root_cgroup(&self) -> Box<Self>;

    /// Creates a new directory for this cgroup.
    ///
    /// Note that this method does not create directories recursively; If a parent of the path does
    /// not exist, an error will be returned. All parent directories must be created before you call
    /// this method.
    ///
    /// Also note that this method does not verify that the subsystem directory (e.g.
    /// `/sys/fs/cgroup/cpu`) is a mount point of a cgroup file system. No error is returned in
    /// this case.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to create the directory, with kind [`ErrorKind::Io`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let mut cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// cgroup.create()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ErrorKind::Io`]: ../enum.ErrorKind.html#variant.Io
    fn create(&mut self) -> Result<()> {
        fs::create_dir(self.path()).map_err(Into::into)
    }

    /// Applies a set of resource limits and constraints to this cgroup.
    ///
    /// See also implementors' documentations for their specific behavior.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to apply the resource configuration.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, Resources, SubsystemKind};
    ///
    /// let mut cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// let resources = Resources {
    ///         cpu: cpu::Resources {
    ///             shares: Some(1024),
    ///             cfs_quota_us: Some(500 * 1000),
    ///             cfs_period_us: Some(1000 * 1000),
    ///             ..cpu::Resources::default()
    ///         },
    ///         ..Resources::default()
    ///     };
    ///
    /// cgroup.apply(&resources)?;
    /// # Ok(())
    /// # }
    /// ```
    fn apply(&mut self, resources: &Resources) -> Result<()>;

    /// Deletes the directory of this cgroup.
    ///
    /// Deleting the directory will fail if this cgroup is in use, i.e. a task is still attached.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to delete the directory, with kind [`ErrorKind::Io`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let mut cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// cgroup.create()?;
    ///
    /// cgroup.delete()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ErrorKind::Io`]: ../enum.ErrorKind.html#variant.Io
    fn delete(&mut self) -> Result<()> {
        fs::remove_dir(self.path()).map_err(Into::into)
    }

    gen_getter!(
        cgroup;
        "tasks",
        "a list of tasks attached to this cgroup,"
        : "The resulting tasks are represented by their thread IDs.",
        tasks,
        Vec<Pid>,
        parse_tasks_procs
    );

    with_doc! { concat!(
        "Attaches a task to this cgroup by writing a thread ID to `tasks` file.\n\n",
        gen_doc!(see),
        gen_doc!(err_write; "tasks"),
        gen_doc!(eg_write; cpu, add_task, std::process::id())),
        fn add_task(&mut self, pid: impl Into<Pid>) -> Result<()> {
            fs::write(self.path().join("tasks"), format!("{}", pid.into())).map_err(Into::into)
        }
    }

    /// Removes a task from this cgroup by writing a thread ID to `tasks` file of the root cgroup.
    ///
    /// See the kernel's documentation for more information about this field.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to write to `tasks` file of the root cgroup of the same
    /// subsystem.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::{Pid, v1::{cpu, Cgroup, CgroupPath, SubsystemKind}};
    ///
    /// let mut cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// let pid = Pid::from(std::process::id());
    /// cgroup.add_task(pid)?;
    ///
    /// cgroup.remove_task(pid)?;
    /// # Ok(())
    /// # }
    /// ```
    fn remove_task(&mut self, pid: impl Into<Pid>) -> Result<()> {
        self.root_cgroup().add_task(pid)
    }

    gen_getter!(
        cgroup;
        "cgroup.procs",
        "a list of processes attached to this cgroup,"
        : "The resulting tasks are represented by their PIDs.",
        procs,
        Vec<Pid>,
        parse_tasks_procs
    );

    with_doc! { concat!(
        "Attaches a process to this cgroup, with all threads in the same thread group at once,
         by writing a PID to `cgroup.procs` file.\n\n",
        gen_doc!(see),
        gen_doc!(err_write; "cgroup.procs"),
        gen_doc!(eg_write; cpu, add_proc, std::process::id())),
        fn add_proc(&mut self, pid: impl Into<Pid>) -> Result<()> {
            fs::write(self.path().join("cgroup.procs"), format!("{}", pid.into())).map_err(Into::into)
        }
    }

    /// Removes a process from this cgroup, with all threads in the same thread group at once, by
    /// writing a PID to `cgroup.procs` file of the root cgroup.
    ///
    /// See the kernel's documentation for more information about this field.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to write to `cgroup.procs` file of the root cgroup of the same
    /// subsystem.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::{Pid, v1::{cpu, Cgroup, CgroupPath, SubsystemKind}};
    ///
    /// let mut cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// let pid = Pid::from(std::process::id());
    /// cgroup.add_proc(pid)?;
    ///
    /// cgroup.remove_proc(pid)?;
    /// # Ok(())
    /// # }
    /// ```
    fn remove_proc(&mut self, pid: impl Into<Pid>) -> Result<()> {
        self.root_cgroup().add_proc(pid)
    }

    gen_getter!(
        cgroup;
        "notify_on_release",
        "whether the system executes the executable written in `release_agent` file
         when this cgroup no longer has any task,",
        notify_on_release,
        bool,
        parse_01_bool
    );

    with_doc! { concat!(
        gen_doc!(
            sets;
            "notify_on_release",
            "whether the system executes the executable written in `release_agent` file
             when this cgroup no longer has any task,"
        ),
        gen_doc!(see),
        gen_doc!(err_write; "notify_on_release"),
        gen_doc!(eg_write; cpu, set_notify_on_release, true)),
        fn set_notify_on_release(&mut self, enable: bool) -> Result<()> {
            fs::write(
                self.path().join(NOTIFY_ON_RELEASE),
                format!("{}", enable as i32),
            )
            .map_err(Into::into)
        }
    }

    with_doc! { concat!(
        gen_doc!(
            reads;
            "release_agent",
            "the command to be executed when \"notify on release\" is triggered,
             i.e. this cgroup is emptied of all tasks,"
        ),
        gen_doc!(see),
        _gen_doc!("read and parse", "release_agent"),
        gen_doc!(eg_read; cpu, release_agent)),
        fn release_agent(&self) -> Result<String> {
            use std::io::Read;

            if !self.is_root() {
                return Err(Error::new(ErrorKind::InvalidOperation));
            }

            let mut buf = String::new();
            self.open_file_read(RELEASE_AGENT)?
                .read_to_string(&mut buf)?;

            Ok(buf)
        }
    }

    with_doc! { concat!(
        gen_doc!(
            sets;
            "release_agent",
            "a command to be executed when \"notify on release\" is triggered,
             i.e. this cgroup is emptied of all tasks,"
        ),
        gen_doc!(see),
        _gen_doc!("write to", "release_agent"),
        gen_doc!(eg_write; cpu, set_release_agent, b"/user/local/bin/foo.sh")),
        fn set_release_agent(&mut self, agent_path: impl AsRef<[u8]>) -> Result<()> {
            if !self.is_root() {
                return Err(Error::new(ErrorKind::InvalidOperation));
            }
            fs::write(self.path().join(RELEASE_AGENT), agent_path.as_ref()).map_err(Into::into)
        }
    }

    with_doc! { concat!(
        gen_doc!(
            reads;
            "cgroup.sane_behavior",
            "whether the subsystem of this cgroup is forced to follow \"sane behavior\","
        ),
        gen_doc!(see),
        _gen_doc!("read and parse", "cgroup.sane_behavior"),
        gen_doc!(eg_read; cpu, sane_behavior)),
        fn sane_behavior(&self) -> Result<bool> {
            if !self.is_root() {
                return Err(Error::new(ErrorKind::InvalidOperation));
            }

            self.open_file_read("cgroup.sane_behavior").and_then(parse_01_bool)
        }
    }

    /// Returns whether a file with the given name exists in this cgroup.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// assert!(cgroup.file_exists("cpu.stat"));
    /// assert!(!cgroup.file_exists("does_not_exist"));
    /// # Ok(())
    /// # }
    /// ```
    fn file_exists(&self, name: &str) -> bool {
        self.path().join(name).exists()
    }

    /// Low-level API that opens a file with read access.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to open the file, with kind [`ErrorKind::Io`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// let cpu_stat_file = cgroup.open_file_read("cpu.stat")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ErrorKind::Io`]: ../enum.ErrorKind.html#variant.Io
    fn open_file_read(&self, name: &str) -> Result<File> {
        File::open(self.path().join(name)).map_err(Into::into)
    }

    /// Low-level API that opens a file with write access.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to open the file, with kind [`ErrorKind::Io`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> controlgroup::Result<()> {
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{cpu, Cgroup, CgroupPath, SubsystemKind};
    ///
    /// let mut cgroup = cpu::Subsystem::new(
    ///     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
    ///
    /// let cpu_shares_file = cgroup.open_file_write("cpu.shares")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ErrorKind::Io`]: ../enum.ErrorKind.html#variant.Io
    fn open_file_write(&mut self, name: &str) -> Result<File> {
        fs::OpenOptions::new()
            .write(true)
            .open(self.path().join(name))
            .map_err(Into::into)
    }
}

/// Path to a cgroup in a cgroup file system.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CgroupPath {
    subsystem_root: PathBuf, // e.g. /sys/fs/cgroup/cpu
    name: Option<PathBuf>,   // e.g. students/charlie
}

impl CgroupPath {
    /// Create a new `CgroupPath` with a subsystem kind and a cgroup name.
    ///
    /// The resulting path is the concatenation of 1) the cgroup mount point `/sys/fs/cgroup`, 2)
    /// the standard directory name for the subsystem (e.g. `SubsystemKind::Cpu` => `cpu`), and 3)
    /// the given cgroup name (e.g. `students/charlie`).
    ///
    /// If the name is empty, the resulting path points to the root cgroup of the subsystem.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::{CgroupPath, SubsystemKind};
    ///
    /// let path = CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie"));
    /// ```
    pub fn new(kind: SubsystemKind, name: PathBuf) -> Self {
        Self::with_subsystem_name(kind, name)
    }

    /// Create a new `CgroupPath` with a custom subsystem directory name and a cgroup name.
    ///
    /// The resulting path is the concatenation of 1) the cgroup mount point `/sys/fs/cgroup`, 2)
    /// the given custom directory name, and 3) the given cgroup name (e.g. `students/charlie`).
    ///
    /// If the name is empty, the resulting path points to the root cgroup of the subsystem.
    ///
    /// # Panics
    ///
    /// Panics if `subsystem_name` is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use controlgroup::v1::CgroupPath;
    ///
    /// let path = CgroupPath::with_subsystem_name(
    ///     "cpu_memory",
    ///     PathBuf::from("students/charlie"),
    /// );
    /// ```
    pub fn with_subsystem_name(subsystem_name: impl AsRef<Path>, name: PathBuf) -> Self {
        assert!(
            !subsystem_name.as_ref().as_os_str().is_empty(),
            "Subsystem name must not be empty"
        );

        Self {
            subsystem_root: Path::new(v1::CGROUPFS_MOUNT_POINT).join(subsystem_name),
            name: if name.as_os_str().is_empty() {
                None
            } else {
                Some(name)
            },
        }
    }

    pub(crate) fn to_path_buf(&self) -> PathBuf {
        if let Some(ref name) = self.name {
            self.subsystem_root.join(name)
        } else {
            self.subsystem_root.clone()
        }
    }

    pub(crate) fn is_subsystem_root(&self) -> bool {
        self.name.is_none()
    }

    pub(crate) fn subsystem_root(&self) -> Self {
        Self {
            subsystem_root: self.subsystem_root.clone(),
            name: None,
        }
    }
}

macro_rules! impl_cgroup {
    ($subsystem: ident, $kind: ident, $( $tt: tt )*) => {
        impl crate::v1::Cgroup for $subsystem {
            fn new(path: crate::v1::CgroupPath) -> Self {
                Self { path }
            }

            fn subsystem(&self) -> crate::v1::SubsystemKind {
                crate::v1::SubsystemKind::$kind
            }

            fn path(&self) -> PathBuf {
                self.path.to_path_buf()
            }

            fn is_root(&self) -> bool {
                self.path.is_subsystem_root()
            }

            fn root_cgroup(&self) -> Box<Self> {
                Box::new(Self::new(self.path.subsystem_root()))
            }

            $( $tt )*
        }
    };
}

pub(crate) trait CgroupHelper: Cgroup {
    fn write_file(&mut self, name: &str, val: impl std::fmt::Display) -> Result<()> {
        fs::write(self.path().join(name), format!("{}", val)).map_err(Into::into)
    }
}

impl<T: Cgroup> CgroupHelper for T {}

fn parse_tasks_procs(reader: impl std::io::Read) -> Result<Vec<Pid>> {
    use std::io::{BufRead, BufReader};

    let mut ids = vec![];
    for line in BufReader::new(reader).lines() {
        let id = line?.trim().parse::<u32>()?;
        ids.push(Pid::from(id))
    }

    Ok(ids)
}

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

    #[test]
    fn test_cgroup_subsystem() {
        macro_rules! t {
            ( $( ($subsystem: ident, $kind: ident) ),* $(, )? ) => {{ $(
                let cgroup = v1::$subsystem::Subsystem::new(
                    CgroupPath::new(SubsystemKind::$kind, gen_cgroup_name!()));
                assert_eq!(cgroup.subsystem(), SubsystemKind::$kind);
            )* }};
        }

        t! {
            (cpu, Cpu),
            (cpuset, Cpuset),
            (cpuacct, Cpuacct),
            (memory, Memory),
            (hugetlb, HugeTlb),
            (devices, Devices),
            (blkio, BlkIo),
            (rdma, Rdma),
            (net_prio, NetPrio),
            (net_cls, NetCls),
            (pids, Pids),
            (freezer, Freezer),
            (perf_event, PerfEvent),
        }
    }

    #[test]
    fn test_cgroup_create_delete() -> Result<()> {
        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        assert!(!cgroup.path().exists());

        cgroup.create()?;
        assert!(cgroup.path().exists());

        cgroup.delete()?;
        assert!(!cgroup.path().exists());

        Ok(())
    }

    #[test]
    #[ignore] // must not be executed in parallel
    fn test_cgroup_add_get_remove_tasks() -> Result<()> {
        use std::process::{self, Command};

        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        let pid = Pid::from(process::id());
        cgroup.add_task(pid)?;
        assert_eq!(cgroup.tasks()?, vec![pid]);

        let mut child = Command::new("sleep").arg("1").spawn().unwrap();
        let child_pid = Pid::from(&child);
        cgroup.add_task(child_pid)?; // FIXME: really needed?
        assert!(cgroup.tasks()? == vec![pid, child_pid] || cgroup.tasks()? == vec![child_pid, pid]);

        child.wait()?;
        assert!(cgroup.tasks()? == vec![pid]);

        cgroup.remove_task(pid)?;
        assert!(cgroup.tasks()?.is_empty());

        cgroup.delete()
    }

    #[test]
    #[ignore] // must not be executed in parallel
    fn test_cgroup_add_get_remove_procs() -> Result<()> {
        use std::process::{self, Command};

        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        let pid = Pid::from(process::id());
        cgroup.add_proc(pid)?;
        assert_eq!(cgroup.procs()?, vec![pid]);

        // automatically added to the cgroup
        let mut child = Command::new("sleep").arg("1").spawn().unwrap();
        let child_pid = Pid::from(&child);
        assert!(cgroup.procs()? == vec![pid, child_pid] || cgroup.procs()? == vec![child_pid, pid]);

        child.wait()?;
        assert!(cgroup.procs()? == vec![pid]);

        cgroup.remove_proc(pid)?;
        assert!(cgroup.procs()?.is_empty());

        cgroup.delete()
    }

    #[test]
    fn test_cgroup_notify_on_release() -> Result<()> {
        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;
        assert_eq!(cgroup.notify_on_release()?, false);

        cgroup.set_notify_on_release(true)?;
        assert_eq!(cgroup.notify_on_release()?, true);

        cgroup.delete()
    }

    #[test]
    #[ignore] // (temporarily) overrides the root cgroup
    fn test_cgroup_release_agent() -> Result<()> {
        let mut root = cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, PathBuf::new()));
        let agent = root.release_agent()?;

        root.set_release_agent(b"foo")?;
        assert_eq!(root.release_agent()?, "foo\n".to_string());

        root.set_release_agent(&agent)?;
        assert_eq!(root.release_agent()?, agent);

        Ok(())
    }

    #[test]
    fn err_cgroup_release_agent() -> Result<()> {
        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        assert_eq!(
            cgroup.release_agent().unwrap_err().kind(),
            ErrorKind::InvalidOperation
        );
        assert_eq!(
            cgroup.set_release_agent(b"foo").unwrap_err().kind(),
            ErrorKind::InvalidOperation
        );

        cgroup.delete()
    }

    #[test]
    fn test_cgroup_sane_behavior() -> Result<()> {
        let root = cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, PathBuf::new()));
        assert_eq!(root.sane_behavior()?, false);

        Ok(())
    }

    #[test]
    fn err_cgroup_sane_behavior() -> Result<()> {
        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        assert_eq!(
            cgroup.sane_behavior().unwrap_err().kind(),
            ErrorKind::InvalidOperation
        );

        cgroup.delete()
    }

    #[test]
    fn test_cgroup_file_exists() -> Result<()> {
        // root
        let root = cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, PathBuf::new()));
        assert!([
            "tasks",
            "cgroup.procs",
            NOTIFY_ON_RELEASE,
            RELEASE_AGENT,
            "cgroup.sane_behavior",
        ]
        .iter()
        .all(|f| root.file_exists(f)));
        assert!(!root.file_exists("does_not_exist"));

        // non-root
        let files = ["tasks", "cgroup.procs", NOTIFY_ON_RELEASE];
        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        assert!(files.iter().all(|f| cgroup.file_exists(f)));
        assert!(!cgroup.file_exists("does_not_exist"));

        cgroup.delete()?;
        assert!(files.iter().all(|f| !cgroup.file_exists(f)));

        Ok(())
    }

    #[test]
    fn test_cgroup_open_file_read_write() -> Result<()> {
        use std::io::{Read, Write};

        let mut cgroup =
            cpu::Subsystem::new(CgroupPath::new(SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        // read
        let mut buf = String::new();
        cgroup
            .open_file_read(NOTIFY_ON_RELEASE)?
            .read_to_string(&mut buf)
            .unwrap();
        assert_eq!(buf, "0\n");

        // write
        let mut file = cgroup.open_file_write(NOTIFY_ON_RELEASE)?;
        write!(file, "1").unwrap();

        // read
        buf.clear();
        cgroup
            .open_file_read(NOTIFY_ON_RELEASE)?
            .read_to_string(&mut buf)
            .unwrap();
        assert_eq!(buf, "1\n");

        cgroup.delete()
    }

    #[test]
    fn test_cgroup_path_new() {
        let path = CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie"));
        assert_eq!(
            path.to_path_buf(),
            PathBuf::from("/sys/fs/cgroup/cpu/students/charlie")
        );
    }

    #[test]
    fn test_cgroup_path_with_subsystem_name() {
        let path = CgroupPath::with_subsystem_name("cpu_memory", PathBuf::from("students/charlie"));
        assert_eq!(
            path.to_path_buf(),
            PathBuf::from("/sys/fs/cgroup/cpu_memory/students/charlie")
        );
    }

    #[test]
    #[should_panic]
    fn panic_cgroup_path_with_subsystem_name() {
        CgroupPath::with_subsystem_name("", PathBuf::from("students/charlie"));
    }

    #[test]
    fn test_cgroup_path_subsystem_root() {
        let path = CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie"));
        assert!(!path.is_subsystem_root());

        let root = path.subsystem_root();
        assert!(root.is_subsystem_root());
        assert_eq!(root.to_path_buf(), PathBuf::from("/sys/fs/cgroup/cpu"),);
    }

    #[test]
    fn test_parse_tasks_procs() -> Result<()> {
        const CONTENT_OK: &str = "\
1
2
3
";

        assert_eq!(
            parse_tasks_procs(CONTENT_OK.as_bytes())?,
            vec![1.into(), 2.into(), 3.into()]
        );

        const CONTENT_NG: &str = "\
1
2
invalid
";

        assert_eq!(
            parse_tasks_procs(CONTENT_NG.as_bytes()).unwrap_err().kind(),
            ErrorKind::Parse
        );

        Ok(())
    }
}