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
//! Operations on a CPU subsystem.
//!
//! [`Subsystem`] implements [`Cgroup`] trait and subsystem-specific operations.
//!
//! For more information about this subsystem, see the kernel's documentation
//! [Documentation/scheduler/sched-design-CFS.txt]
//! paragraph 7 ("GROUP SCHEDULER EXTENSIONS TO CFS"), and [Documentation/scheduler/sched-bwc.txt].
//!
//! # Examples
//!
//! ```no_run
//! # fn main() -> controlgroup::Result<()> {
//! use std::path::PathBuf;
//! use controlgroup::{Pid, v1::{self, cpu, Cgroup, CgroupPath, SubsystemKind}};
//!
//! let mut cpu_cgroup = cpu::Subsystem::new(
//!     CgroupPath::new(SubsystemKind::Cpu, PathBuf::from("students/charlie")));
//! cpu_cgroup.create()?;
//!
//! // Define a resource limit about how a cgroup can use CPU time.
//! let resources = cpu::Resources {
//!     shares: Some(1024),
//!     cfs_quota_us: Some(500_000),
//!     cfs_period_us: Some(1_000_000),
//!     ..cpu::Resources::default()
//! };
//!
//! // Apply the resource limit to this cgroup.
//! cpu_cgroup.apply(&resources.into())?;
//!
//! // Add tasks to this cgroup.
//! let pid = Pid::from(std::process::id());
//! cpu_cgroup.add_task(pid)?;
//!
//! // Do something ...
//!
//! // Get the throttling statistics of this cgroup.
//! println!("{:?}", cpu_cgroup.stat()?);
//!
//! cpu_cgroup.remove_task(pid)?;
//! cpu_cgroup.delete()?;
//! # Ok(())
//! # }
//! ```
//!
//! [`Subsystem`]: struct.Subsystem.html
//! [`Cgroup`]: ../trait.Cgroup.html
//!
//! [Documentation/scheduler/sched-design-CFS.txt]: https://www.kernel.org/doc/Documentation/scheduler/sched-design-CFS.txt
//! [Documentation/scheduler/sched-bwc.txt]: https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt

use std::path::PathBuf;

use crate::{
    parse::{parse, parse_next},
    v1::{self, cgroup::CgroupHelper, Cgroup, CgroupPath},
    Result,
};

/// Handler of a CPU subsystem.
#[derive(Debug)]
pub struct Subsystem {
    path: CgroupPath,
}

/// Resource limit on how much CPU time a cgroup can use.
///
/// See the kernel's documentation for more information about the fields.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Resources {
    /// Weight of how much of the total CPU time should be provided to this cgroup.
    pub shares: Option<u64>,
    /// Total available CPU time for this cgroup within a period (in microseconds).
    ///
    /// Setting -1 removes the current limit.
    pub cfs_quota_us: Option<i64>,
    /// Length of a period (in microseconds).
    pub cfs_period_us: Option<u64>,

    /// Total available CPU time for realtime tasks in this cgroup within a period (in microseconds).
    ///
    /// Setting -1 removes the current limit.
    pub rt_runtime_us: Option<i64>,
    /// Length of a period for realtime tasks (in microseconds).
    pub rt_period_us: Option<u64>,
}

/// Throttling statistics of a cgroup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stat {
    /// Number of periods (as specified in [`Resources.cfs_period_us`]) that have elapsed.
    ///
    /// [`Resources.cfs_period_us`]: struct.Resources.html#structfield.cfs_period_us
    pub nr_periods: u64,
    /// Number of times this cgroup has been throttled.
    pub nr_throttled: u64,
    /// Total time duration for which this cgroup has been throttled (in nanoseconds).
    pub throttled_time: u64,
}

impl_cgroup! {
    Subsystem, Cpu,

    /// Applies the `Some` fields in `resources.cpu`.
    fn apply(&mut self, resources: &v1::Resources) -> Result<()> {
        let res: &self::Resources = &resources.cpu;

        macro_rules! a {
            ($field: ident, $setter: ident) => {
                if let Some(r) = res.$field {
                    self.$setter(r)?;
                }
            };
        }

        a!(shares, set_shares);
        a!(cfs_quota_us, set_cfs_quota_us);
        a!(cfs_period_us, set_cfs_period_us);
        a!(rt_runtime_us, set_rt_runtime_us);
        a!(rt_period_us, set_rt_period_us);

        Ok(())
    }
}

impl Subsystem {
    gen_getter!(
        cpu,
        "the throttling statistics of this cgroup",
        stat,
        Stat,
        parse_stat
    );

    gen_getter!(cpu, "the CPU time shares", shares: link, u64, parse);
    gen_setter!(cpu, "CPU time shares", shares: link, set_shares, u64, 2048);

    gen_getter!(
        cpu,
        "the total available CPU time within a period (in microseconds)",
        cfs_quota_us: link,
        i64,
        parse
    );
    gen_setter!(
        cpu,
        "total available CPU time within a period (in microseconds)"
            : "Setting -1 removes the current limit.",
        cfs_quota_us : link,
        set_cfs_quota_us,
        quota: i64,
        500 * 1000
    );

    gen_getter!(
        cpu,
        "the length of period (in microseconds)",
        cfs_period_us: link,
        u64,
        parse
    );
    gen_setter!(
        cpu,
        "length of period (in microseconds)",
        cfs_period_us: link,
        set_cfs_period_us,
        period: u64,
        1000 * 1000
    );

    gen_getter!(
        cpu,
        "the total available CPU time for realtime tasks within a period (in microseconds)",
        rt_runtime_us: link,
        i64,
        parse
    );
    gen_setter!(
        cpu,
        "total available CPU time for realtime tasks within a period (in microseconds)"
            : "Setting -1 removes the current limit.",
        rt_runtime_us : link,
        set_rt_runtime_us,
        runtime: i64,
        500 * 1000
    );

    gen_getter!(
        cpu,
        "the length of period for realtime tasks (in microseconds)",
        rt_period_us: link,
        u64,
        parse
    );
    gen_setter!(
        cpu,
        "the length of period for realtime tasks (in microseconds)",
        rt_period_us: link,
        set_rt_period_us,
        period: u64,
        1000 * 1000
    );
}

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

    let (mut nr_periods, mut nr_throttled, mut throttled_time) = (None, None, None);

    for line in BufReader::new(reader).lines() {
        let line = line?;
        let mut entry = line.split_whitespace();

        match entry.next() {
            Some("nr_periods") => {
                if nr_periods.is_some() {
                    bail_parse!();
                }
                nr_periods = Some(parse_next(&mut entry)?);
            }
            Some("nr_throttled") => {
                if nr_throttled.is_some() {
                    bail_parse!();
                }
                nr_throttled = Some(parse_next(&mut entry)?);
            }
            Some("throttled_time") => {
                if throttled_time.is_some() {
                    bail_parse!();
                }
                throttled_time = Some(parse_next(&mut entry)?);
            }
            _ => bail_parse!(),
        };

        if entry.next().is_some() {
            bail_parse!();
        }
    }

    match (nr_periods, nr_throttled, throttled_time) {
        (Some(nr_periods), Some(nr_throttled), Some(throttled_time)) => Ok(Stat {
            nr_periods,
            nr_throttled,
            throttled_time,
        }),
        _ => {
            bail_parse!();
        }
    }
}

impl Into<v1::Resources> for Resources {
    fn into(self) -> v1::Resources {
        v1::Resources {
            cpu: self,
            ..v1::Resources::default()
        }
    }
}

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

    #[test]
    fn test_subsystem_create_file_exists() -> Result<()> {
        gen_subsystem_test!(Cpu, ["stat", "shares", "cfs_quota_us", "cfs_period_us"])
    }

    #[test]
    fn test_subsystem_apply() -> Result<()> {
        gen_subsystem_test!(
            Cpu,
            Resources {
                shares: Some(1024),
                cfs_quota_us: Some(100_000),
                cfs_period_us: Some(1_000_000),
                rt_runtime_us: None,
                rt_period_us: None,
            },
            (shares, 1024),
            (cfs_quota_us, 100_000),
            (cfs_period_us, 1_000_000)
        )
    }

    #[test]
    fn test_subsystem_stat() -> Result<()> {
        gen_subsystem_test!(
            Cpu,
            stat,
            Stat {
                nr_periods: 0,
                nr_throttled: 0,
                throttled_time: 0
            }
        )
    }

    #[test]
    #[ignore] // must not executed in parallel
    fn test_subsystem_stat_throttled() -> Result<()> {
        let mut cgroup =
            Subsystem::new(CgroupPath::new(v1::SubsystemKind::Cpu, gen_cgroup_name!()));
        cgroup.create()?;

        let pid = crate::Pid::from(std::process::id());
        cgroup.add_proc(pid)?;

        cgroup.set_cfs_quota_us(1000)?; // 1%

        crate::consume_cpu_until(|| cgroup.stat().unwrap().nr_throttled > 0, 30);
        // dbg!(cgroup.stat()?);

        let stat = cgroup.stat()?;
        assert!(stat.nr_periods > 0);
        assert!(stat.throttled_time > 0);

        cgroup.remove_proc(pid)?;
        cgroup.delete()
    }

    #[test]
    fn test_subsystem_shares() -> Result<()> {
        gen_subsystem_test!(Cpu, shares, 1024, set_shares, 2048)
    }

    #[test]
    fn test_subsystem_cfs_quota_us() -> Result<()> {
        gen_subsystem_test!(Cpu, cfs_quota_us, -1, set_cfs_quota_us, 100 * 1000)
    }

    #[test]
    fn test_subsystem_cfs_period_us() -> Result<()> {
        gen_subsystem_test!(
            Cpu,
            cfs_period_us,
            100 * 1000,
            set_cfs_period_us,
            1000 * 1000
        )
    }

    #[test]
    fn test_parse_stat() -> Result<()> {
        const CONTENT_OK: &str = "\
nr_periods 256
nr_throttled 8
throttled_time 32
";

        assert_eq!(
            parse_stat(CONTENT_OK.as_bytes())?,
            Stat {
                nr_periods: 256,
                nr_throttled: 8,
                throttled_time: 32
            }
        );

        assert_eq!(
            parse_stat("".as_bytes()).unwrap_err().kind(),
            ErrorKind::Parse
        );

        const CONTENT_NG_NOT_INT: &str = "\
nr_periods invalid
nr_throttled 8
throttled_time 32
";

        const CONTENT_NG_MISSING_DATA: &str = "\
nr_periods 256
throttled_time 32
";

        const CONTENT_NG_EXTRA_DATA: &str = "\
nr_periods 256
nr_throttled 8 256
throttled_time 32
";

        const CONTENT_NG_EXTRA_ROW: &str = "\
nr_periods 256
nr_throttled 8
throttled_time 32
invalid 256
";

        for case in &[
            CONTENT_NG_NOT_INT,
            CONTENT_NG_MISSING_DATA,
            CONTENT_NG_EXTRA_DATA,
            CONTENT_NG_EXTRA_ROW,
        ] {
            assert_eq!(
                parse_stat(case.as_bytes()).unwrap_err().kind(),
                ErrorKind::Parse
            );
        }

        Ok(())
    }
}