patches and low-level development discussion
 help / color / mirror / code / Atom feed
blob eb9b892ab6f562cffa738abaf9c55dc18001012a 6360 bytes (raw)
name: tools/cgroup-setup/src/cgroup.rs 	 # note: path name is non-authoritative(*)

  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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
 
// SPDX-License-Identifier: EUPL-1.2+
// SPDX-FileCopyrightText: 2026 Demi Marie Obenour <demiobenour@gmail.com>

use std::fs::File;
use std::io::{Read as _, Seek as _, Write as _};
use std::os::unix::prelude::*;

use std::path::{Path, PathBuf};

use rustix::fs::{AtFlags, XattrFlags};
use rustix::path::Arg;
use rustix::{
    fs::{Mode, OFlags, ResolveFlags},
    io::Errno,
};

pub(crate) struct LeafCgroup {
    path: PathBuf,
    fd: OwnedFd,
}

pub enum Access {
    Read,
    Write,
}

impl LeafCgroup {
    pub fn enable_delegation(&self) -> Result<(), Errno> {
        rustix::fs::fsetxattr(self.fd.as_fd(), c"user.delegate", b"1", XattrFlags::empty())
    }

    pub fn open_subtree(&self, path: &std::path::Path, access: Access) -> Result<OwnedFd, Errno> {
        rustix::fs::openat2(
            self.fd.as_fd(),
            path,
            OFlags::NOATIME
                | OFlags::CLOEXEC
                | OFlags::NOFOLLOW
                | match access {
                    Access::Write => OFlags::WRONLY,
                    Access::Read => OFlags::RDONLY,
                },
            Mode::empty(),
            ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH | ResolveFlags::NO_XDEV,
        )
    }

    pub fn wait_for_empty(&self, kill: bool) -> std::io::Result<()> {
        let kill_fd = if kill {
            Some(self.open_subtree(std::path::Path::new("cgroup.kill"), Access::Write)?)
        } else {
            None
        };
        let wait_file = self.open_subtree(std::path::Path::new("cgroup.events"), Access::Read)?;
        let poll_fd = wait_file.as_raw_fd();
        let mut wait_fd = File::from(wait_file);
        if let Some(kill_fd) = kill_fd {
            assert_eq!(rustix::io::write(kill_fd.as_fd(), b"1")?, 1, "kernel bug");
        }
        let mut fds = libc::pollfd {
            fd: poll_fd,
            events: libc::POLLPRI | libc::POLLERR,
            revents: 0,
        };
        let mut v = vec![];
        loop {
            v.clear();
            // SAFETY: FFI call, valid arguments, fds contains 1 element
            if unsafe { libc::poll(&raw mut fds, 1, -1) } != 1 {
                panic!("poll failed");
            }
            wait_fd
                .seek(std::io::SeekFrom::Start(0))
                .expect("Seek on control group file should succeed");
            wait_fd
                .read_to_end(&mut v)
                .expect("reading from control group should work");
            if v.split(|&c| c == b'\n').any(|line| line == b"populated 0") {
                break;
            }
        }
        Ok(())
    }
}

impl AsFd for LeafCgroup {
    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
        self.fd.as_fd()
    }
}

impl LeafCgroup {
    pub(crate) fn open_cgroup_at(&self, p: &Path) -> Result<Self, Errno> {
        let fd = rustix::fs::openat2(
            self.fd.as_fd(),
            p,
            OFlags::NOATIME
                | OFlags::CLOEXEC
                | OFlags::NOFOLLOW
                | OFlags::RDONLY
                | OFlags::DIRECTORY,
            Mode::empty(),
            ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH | ResolveFlags::NO_XDEV,
        )?;
        Ok(Self {
            fd,
            path: self.path.join(p),
        })
    }
    pub(crate) fn open_cgroup(fd: BorrowedFd, p: &Path) -> Result<Self, Errno> {
        let fd = rustix::fs::openat2(
            fd,
            p,
            OFlags::NOATIME
                | OFlags::CLOEXEC
                | OFlags::NOFOLLOW
                | OFlags::RDONLY
                | OFlags::DIRECTORY,
            Mode::empty(),
            ResolveFlags::NO_SYMLINKS,
        )?;
        Ok(Self {
            fd,
            path: p.to_owned(),
        })
    }
    pub(crate) fn make_child(&self, p: &Path) -> Result<(), Errno> {
        let r = rustix::fs::mkdirat(
            self.fd.as_fd(),
            p,
            Mode::RUSR
                | Mode::WUSR
                | Mode::XUSR
                | Mode::RGRP
                | Mode::XGRP
                | Mode::ROTH
                | Mode::XOTH,
        );
        if r == Err(Errno::EXIST) { Ok(()) } else { r }
    }

    pub(crate) fn delete_child(&self, path: &Path) -> Result<(), Errno> {
        remove_all(100, self.as_fd(), &path.as_cow_c_str().unwrap())
    }

    pub(crate) fn write_cgroup_value(&self, name: &str, value: &str) -> Result<(), String> {
        let path = Path::new(name);
        let fd = rustix::fs::openat2(
            self.as_fd(),
            path,
            OFlags::NOATIME | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::WRONLY,
            Mode::empty(),
            ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH | ResolveFlags::NO_XDEV,
        )
        .map_err(|e| format!("Cannot open {:?}: {}", path, e))?;
        File::from(fd)
            .write_all(value.as_bytes())
            .map_err(|e| format!("Cannot write {:?} to {:?}: {}", value, path, e))
    }
}

fn remove_recursively(fd: OwnedFd, remaining_depth: usize) -> Result<(), Errno> {
    if remaining_depth < 1 {
        panic!("control groups too deeply nested");
    }
    let mut d = rustix::fs::Dir::new(fd).expect("cannot start iterating");
    while let Some(element) = d.next() {
        let element = element.expect("Iterating through a cgroup directory failed?");
        if element.file_type() != rustix::fs::FileType::Directory {
            continue;
        }

        let remaining_depth = remaining_depth - 1;
        let d: &rustix::fs::Dir = &d;
        let dirfd = d.fd().unwrap();
        let path = element.file_name();
        remove_all(remaining_depth, dirfd, path)?;
    }
    Ok(())
}

fn remove_all(
    remaining_depth: usize,
    dirfd: BorrowedFd<'_>,
    path: &std::ffi::CStr,
) -> Result<(), Errno> {
    if path == c"." || path == c".." {
        return Ok(());
    }
    if rustix::fs::unlinkat(dirfd, path, AtFlags::REMOVEDIR).is_ok() {
        return Ok(());
    }
    let fd = rustix::fs::openat2(
        dirfd,
        path,
        OFlags::NOATIME | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::RDONLY | OFlags::DIRECTORY,
        Mode::empty(),
        ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH | ResolveFlags::NO_XDEV,
    )?;
    remove_recursively(fd, remaining_depth)?;
    rustix::fs::unlinkat(dirfd, path, AtFlags::REMOVEDIR)?;
    Ok(())
}

debug log:

solving eb9b892ab6f562cffa738abaf9c55dc18001012a ...
found eb9b892ab6f562cffa738abaf9c55dc18001012a in https://inbox.spectrum-os.org/spectrum-devel/20260711-cgroups-v3-3-5cba61a20cba@gmail.com/

applying [1/1] https://inbox.spectrum-os.org/spectrum-devel/20260711-cgroups-v3-3-5cba61a20cba@gmail.com/
diff --git a/tools/cgroup-setup/src/cgroup.rs b/tools/cgroup-setup/src/cgroup.rs
new file mode 100644
index 0000000000000000000000000000000000000000..eb9b892ab6f562cffa738abaf9c55dc18001012a

Checking patch tools/cgroup-setup/src/cgroup.rs...
Applied patch tools/cgroup-setup/src/cgroup.rs cleanly.

index at:
100644 eb9b892ab6f562cffa738abaf9c55dc18001012a	tools/cgroup-setup/src/cgroup.rs

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://spectrum-os.org/git/doc
	https://spectrum-os.org/git/mktuntap
	https://spectrum-os.org/git/spectrum
	https://spectrum-os.org/git/ucspi-vsock

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).