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
//! This module contains the implementation of the `cpuacct` cgroup subsystem.
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//!  [Documentation/cgroup-v1/cpuacct.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpuacct.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;

use error::*;
use error::ErrorKind::*;

use {ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};

/// A controller that allows controlling the `cpuacct` subsystem of a Cgroup.
///
/// In essence, this control group provides accounting (hence the name `cpuacct`) for CPU usage of
/// the tasks in the control group.
#[derive(Debug, Clone)]
pub struct CpuAcctController {
    base: PathBuf,
    path: PathBuf,
}

/// Represents the statistics retrieved from the control group.
pub struct CpuAcct {
    /// Divides the time used by the tasks into `user` time and `system` time.
    pub stat: String,
    /// Total CPU time (in nanoseconds) spent by the tasks.
    pub usage: u64,
    /// Total CPU time (in nanoseconds) spent by the tasks, broken down by CPU and by whether the
    /// time spent is `user` time or `system` time.
    ///
    /// An example is as follows:
    /// ```text
    /// cpu user system
    /// 0 8348363768 0
    /// 1 8324369100 0
    /// 2 8598185449 0
    /// 3 8648262473 0
    /// ```
    pub usage_all: String,
    /// CPU time (in nanoseconds) spent by the tasks, broken down by each CPU.
    /// Times spent in each CPU are separated by a space.
    pub usage_percpu: String,
    /// As for `usage_percpu`, but the `system` time spent.
    pub usage_percpu_sys: String,
    /// As for `usage_percpu`, but the `user` time spent.
    pub usage_percpu_user: String,
    /// CPU time (in nanoseconds) spent by the tasks that counted for `system` time.
    pub usage_sys: u64,
    /// CPU time (in nanoseconds) spent by the tasks that counted for `user` time.
    pub usage_user: u64,
}

impl ControllerInternal for CpuAcctController {
    fn control_type(&self) -> Controllers {
        Controllers::CpuAcct
    }
    fn get_path(&self) -> &PathBuf {
        &self.path
    }
    fn get_path_mut(&mut self) -> &mut PathBuf {
        &mut self.path
    }
    fn get_base(&self) -> &PathBuf {
        &self.base
    }

    fn apply(&self, _res: &Resources) -> Result<()> {
        Ok(())
    }
}

impl ControllIdentifier for CpuAcctController {
    fn controller_type() -> Controllers {
        Controllers::CpuAcct
    }
}

impl<'a> From<&'a Subsystem> for &'a CpuAcctController {
    fn from(sub: &'a Subsystem) -> &'a CpuAcctController {
        unsafe {
            match sub {
                Subsystem::CpuAcct(c) => c,
                _ => {
                    assert_eq!(1, 0);
                    ::std::mem::uninitialized()
                }
            }
        }
    }
}

fn read_u64_from(mut file: File) -> Result<u64> {
    let mut string = String::new();
    let res = file.read_to_string(&mut string);
    match res {
        Ok(_) => match string.trim().parse() {
            Ok(e) => Ok(e),
            Err(e) => Err(Error::with_cause(ParseError, e)),
        },
        Err(e) => Err(Error::with_cause(ReadFailed, e)),
    }
}

fn read_string_from(mut file: File) -> Result<String> {
    let mut string = String::new();
    match file.read_to_string(&mut string) {
        Ok(_) => Ok(string.trim().to_string()),
        Err(e) => Err(Error::with_cause(ReadFailed, e)),
    }
}

impl CpuAcctController {
    /// Contructs a new `CpuAcctController` with `oroot` serving as the root of the control group.
    pub fn new(oroot: PathBuf) -> Self {
        let mut root = oroot;
        root.push(Self::controller_type().to_string());
        Self {
            base: root.clone(),
            path: root,
        }
    }

    /// Gathers the statistics that are available in the control group into a `CpuAcct` structure.
    pub fn cpuacct(&self) -> CpuAcct {
        CpuAcct {
            stat: self
                .open_path("cpuacct.stat", false)
                .and_then(|file| read_string_from(file))
                .unwrap_or("".to_string()),
            usage: self
                .open_path("cpuacct.usage", false)
                .and_then(|file| read_u64_from(file))
                .unwrap_or(0),
            usage_all: self
                .open_path("cpuacct.usage_all", false)
                .and_then(|file| read_string_from(file))
                .unwrap_or("".to_string()),
            usage_percpu: self
                .open_path("cpuacct.usage_percpu", false)
                .and_then(|file| read_string_from(file))
                .unwrap_or("".to_string()),
            usage_percpu_sys: self
                .open_path("cpuacct.usage_percpu_sys", false)
                .and_then(|file| read_string_from(file))
                .unwrap_or("".to_string()),
            usage_percpu_user: self
                .open_path("cpuacct.usage_percpu_user", false)
                .and_then(|file| read_string_from(file))
                .unwrap_or("".to_string()),
            usage_sys: self
                .open_path("cpuacct.usage_sys", false)
                .and_then(|file| read_u64_from(file))
                .unwrap_or(0),
            usage_user: self
                .open_path("cpuacct.usage_user", false)
                .and_then(|file| read_u64_from(file))
                .unwrap_or(0),
        }
    }

    /// Reset the statistics the kernel has gathered about the control group.
    pub fn reset(&self) -> Result<()> {
        self.open_path("cpuacct.usage", true)
            .and_then(|mut file| file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)))
    }
}