cgroups_rs/fs/
net_prio.rs

1// Copyright (c) 2018 Levente Kurusa
2//
3// SPDX-License-Identifier: Apache-2.0 or MIT
4//
5
6//! This module contains the implementation of the `net_prio` cgroup subsystem.
7//!
8//! See the Kernel's documentation for more information about this subsystem, found at:
9//!  [Documentation/cgroup-v1/net_prio.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_prio.txt)
10use std::collections::HashMap;
11use std::io::{BufRead, BufReader, Write};
12use std::path::PathBuf;
13
14use crate::fs::error::ErrorKind::*;
15use crate::fs::error::*;
16
17use crate::fs::read_u64_from;
18use crate::fs::{
19    ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem,
20};
21
22/// A controller that allows controlling the `net_prio` subsystem of a Cgroup.
23///
24/// In essence, using `net_prio` one can set the priority of the packets emitted from the control
25/// group's tasks. This can then be used to have QoS restrictions on certain control groups and
26/// thus, prioritizing certain tasks.
27#[derive(Debug, Clone)]
28pub struct NetPrioController {
29    base: PathBuf,
30    path: PathBuf,
31}
32
33impl ControllerInternal for NetPrioController {
34    fn control_type(&self) -> Controllers {
35        Controllers::NetPrio
36    }
37    fn get_path(&self) -> &PathBuf {
38        &self.path
39    }
40    fn get_path_mut(&mut self) -> &mut PathBuf {
41        &mut self.path
42    }
43    fn get_base(&self) -> &PathBuf {
44        &self.base
45    }
46
47    fn apply(&self, res: &Resources) -> Result<()> {
48        // get the resources that apply to this controller
49        let res: &NetworkResources = &res.network;
50
51        for i in &res.priorities {
52            let _ = self.set_if_prio(&i.name, i.priority);
53        }
54
55        Ok(())
56    }
57}
58
59impl ControllIdentifier for NetPrioController {
60    fn controller_type() -> Controllers {
61        Controllers::NetPrio
62    }
63}
64
65impl<'a> From<&'a Subsystem> for &'a NetPrioController {
66    fn from(sub: &'a Subsystem) -> &'a NetPrioController {
67        unsafe {
68            match sub {
69                Subsystem::NetPrio(c) => c,
70                _ => {
71                    assert_eq!(1, 0);
72                    let v = std::mem::MaybeUninit::uninit();
73                    v.assume_init()
74                }
75            }
76        }
77    }
78}
79
80impl NetPrioController {
81    /// Constructs a new `NetPrioController` with `root` serving as the root of the control group.
82    pub fn new(point: PathBuf, root: PathBuf) -> Self {
83        Self {
84            base: root,
85            path: point,
86        }
87    }
88
89    /// Retrieves the current priority of the emitted packets.
90    pub fn prio_idx(&self) -> u64 {
91        self.open_path("net_prio.prioidx", false)
92            .and_then(read_u64_from)
93            .unwrap_or(0)
94    }
95
96    /// A map of priorities for each network interface.
97    pub fn ifpriomap(&self) -> Result<HashMap<String, u64>> {
98        self.open_path("net_prio.ifpriomap", false)
99            .and_then(|file| {
100                let bf = BufReader::new(file);
101                bf.lines()
102                    .map(|line| {
103                        let line = line.map_err(|_| Error::new(ParseError))?;
104                        let mut parts = line.split_whitespace();
105
106                        let ifname = parts.next().ok_or(Error::new(ParseError))?;
107                        let ifprio_str = parts.next().ok_or(Error::new(ParseError))?;
108
109                        let ifprio = ifprio_str
110                            .trim()
111                            .parse()
112                            .map_err(|e| Error::with_cause(ParseError, e))?;
113
114                        Ok((ifname.to_string(), ifprio))
115                    })
116                    .collect::<Result<HashMap<String, _>>>()
117            })
118    }
119
120    /// Set the priority of the network traffic on `eif` to be `prio`.
121    pub fn set_if_prio(&self, eif: &str, prio: u64) -> Result<()> {
122        self.open_path("net_prio.ifpriomap", true)
123            .and_then(|mut file| {
124                file.write_all(format!("{} {}", eif, prio).as_ref())
125                    .map_err(|e| {
126                        Error::with_cause(
127                            WriteFailed(
128                                "net_prio.ifpriomap".to_string(),
129                                format!("{} {}", eif, prio),
130                            ),
131                            e,
132                        )
133                    })
134            })
135    }
136}