Skip to main content

libcontainer/container/
container_events.rs

1use std::thread;
2use std::time::Duration;
3
4use libcgroups::common::CgroupManager;
5
6use super::{Container, ContainerStatus};
7use crate::error::LibcontainerError;
8
9impl Container {
10    /// Displays container events
11    ///
12    /// # Example
13    ///
14    /// ```no_run
15    /// use libcontainer::container::builder::ContainerBuilder;
16    /// use libcontainer::syscall::syscall::SyscallType;
17    ///
18    /// # fn main() -> anyhow::Result<()> {
19    /// let mut container = ContainerBuilder::new(
20    ///     "74f1a4cb3801".to_owned(),
21    ///     SyscallType::default(),
22    /// )
23    /// .as_init("/var/run/docker/bundle")
24    /// .build()?;
25    ///
26    /// container.events(5000, false)?;
27    /// # Ok(())
28    /// # }
29    /// ```
30    pub fn events(&mut self, interval: u32, stats: bool) -> Result<(), LibcontainerError> {
31        self.refresh_status()?;
32        if !self.state.status.eq(&ContainerStatus::Running) {
33            tracing::error!(id = ?self.id(), status = ?self.state.status, "container is not running");
34            return Err(LibcontainerError::IncorrectStatus(self.status()));
35        }
36
37        let cgroup_manager =
38            libcgroups::common::create_cgroup_manager(libcgroups::common::CgroupConfig {
39                cgroup_path: self.spec()?.cgroup_path,
40                systemd_cgroup: self.systemd(),
41                container_name: self.id().to_string(),
42            })?;
43        match stats {
44            true => {
45                let stats = cgroup_manager.stats()?;
46                println!(
47                    "{}",
48                    serde_json::to_string_pretty(&stats)
49                        .map_err(LibcontainerError::OtherSerialization)?
50                );
51            }
52            false => loop {
53                let stats = cgroup_manager.stats()?;
54                println!(
55                    "{}",
56                    serde_json::to_string_pretty(&stats)
57                        .map_err(LibcontainerError::OtherSerialization)?
58                );
59                thread::sleep(Duration::from_secs(interval as u64));
60            },
61        }
62
63        Ok(())
64    }
65}