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
use std::thread;
use std::time::Duration;
use libcgroups::common::CgroupManager;
use super::{Container, ContainerStatus};
use crate::error::LibcontainerError;
impl Container {
/// Displays container events
///
/// # Example
///
/// ```no_run
/// use libcontainer::container::builder::ContainerBuilder;
/// use libcontainer::syscall::syscall::SyscallType;
///
/// # fn main() -> anyhow::Result<()> {
/// let mut container = ContainerBuilder::new(
/// "74f1a4cb3801".to_owned(),
/// SyscallType::default(),
/// )
/// .as_init("/var/run/docker/bundle")
/// .build()?;
///
/// container.events(5000, false)?;
/// # Ok(())
/// # }
/// ```
pub fn events(&mut self, interval: u32, stats: bool) -> Result<(), LibcontainerError> {
self.refresh_status()?;
if !self.state.status.eq(&ContainerStatus::Running) {
tracing::error!(id = ?self.id(), status = ?self.state.status, "container is not running");
return Err(LibcontainerError::IncorrectStatus(self.status()));
}
let cgroup_manager =
libcgroups::common::create_cgroup_manager(libcgroups::common::CgroupConfig {
cgroup_path: self.spec()?.cgroup_path,
systemd_cgroup: self.systemd(),
container_name: self.id().to_string(),
})?;
match stats {
true => {
let stats = cgroup_manager.stats()?;
println!(
"{}",
serde_json::to_string_pretty(&stats)
.map_err(LibcontainerError::OtherSerialization)?
);
}
false => loop {
let stats = cgroup_manager.stats()?;
println!(
"{}",
serde_json::to_string_pretty(&stats)
.map_err(LibcontainerError::OtherSerialization)?
);
thread::sleep(Duration::from_secs(interval as u64));
},
}
Ok(())
}
}