⎇ c22d2480b93b7802be8e8ea5a0075b8175c4fedc
crates/shared/ente-incarnate/src/cgroup.rs
Historia
Quién tocó qué
crudo
1//! Resolución y creación de cgroups v2 para el hijo.
2
3use crate::error::IncarnateError;
4use brahman_card::CgroupSpec;
5use std::path::PathBuf;
6
7/// Cgroup actual del proceso que llama. Lo usamos como prefijo para paths
8/// declarados relativos en `CgroupSpec.path`.
9pub fn current_cgroup() -> Option<String> {
10 let s = std::fs::read_to_string("/proc/self/cgroup").ok()?;
11 s.lines()
12 .find_map(|l| l.strip_prefix("0::"))
13 .map(|s| s.trim().to_string())
14}
15
16/// Resuelve un path declarado contra la jerarquía real.
17pub fn resolve_cgroup_path(spec_path: &str) -> String {
18 if spec_path.is_empty() {
19 return String::new();
20 }
21 if spec_path.starts_with('/') {
22 return spec_path.to_string();
23 }
24 let trimmed = spec_path.trim_start_matches('/');
25 if let Some(cg) = current_cgroup() {
26 let base = if cg == "/" {
27 String::new()
28 } else {
29 cg.trim_end_matches('/').to_string()
30 };
31 format!("{base}/{trimmed}")
32 } else {
33 format!("/{trimmed}")
34 }
35}
36
37/// Crea el cgroup declarado y aplica weights. Devuelve el path absoluto
38/// resultante bajo `/sys/fs/cgroup`.
39pub fn ensure_cgroup(spec: &CgroupSpec) -> Result<PathBuf, IncarnateError> {
40 let rel = resolve_cgroup_path(&spec.path);
41 if rel.is_empty() {
42 return Err(IncarnateError::CgroupNotWritable {
43 path: PathBuf::from("(empty)"),
44 });
45 }
46 let abs = PathBuf::from(format!("/sys/fs/cgroup{}", rel));
47 std::fs::create_dir_all(&abs).map_err(|e| match e.kind() {
48 std::io::ErrorKind::PermissionDenied => IncarnateError::CgroupNotWritable { path: abs.clone() },
49 _ => IncarnateError::Io(e),
50 })?;
51 if let Some(w) = spec.cpu_weight {
52 let _ = std::fs::write(abs.join("cpu.weight"), format!("{w}\n"));
53 }
54 if let Some(w) = spec.io_weight {
55 // io.weight requiere "default <n>" en cgroup v2.
56 let _ = std::fs::write(abs.join("io.weight"), format!("default {w}\n"));
57 }
58 Ok(abs)
59}
60
61/// Mueve `pid` a `cgroup_abs/cgroup.procs`.
62pub fn move_to_cgroup(cgroup_abs: &std::path::Path, pid: nix::unistd::Pid) -> Result<(), IncarnateError> {
63 let procs = cgroup_abs.join("cgroup.procs");
64 std::fs::write(&procs, format!("{}\n", pid.as_raw())).map_err(|e| match e.kind() {
65 std::io::ErrorKind::PermissionDenied => IncarnateError::CgroupNotWritable {
66 path: procs.clone(),
67 },
68 _ => IncarnateError::Io(e),
69 })
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 #[test]
77 fn absolute_path_passthrough() {
78 assert_eq!(resolve_cgroup_path("/foo/bar"), "/foo/bar");
79 }
80
81 #[test]
82 fn empty_returns_empty() {
83 assert_eq!(resolve_cgroup_path(""), "");
84 }
85
86 #[test]
87 fn relative_path_prefixed() {
88 let r = resolve_cgroup_path("shipote/ws-1");
89 assert!(r.ends_with("/shipote/ws-1") || r == "/shipote/ws-1");
90 }
91}