patches and low-level development discussion
 help / color / mirror / code / Atom feed
blob cd77becc0b40bfdcd983e53b63b7c21e4308d5fc 5513 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
 
// SPDX-License-Identifier: EUPL-1.2+
// SPDX-FileCopyrightText: 2026 Demi Marie Obenour <demiobenour@gmail.com>

use std::fs::File;
use std::io::{Read, Seek};
use std::os::fd::{AsFd, OwnedFd};
use std::os::fd::{AsRawFd, BorrowedFd};

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

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

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

enum Access {
    Read,
    Write,
}

impl LeafCgroup {
    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 kill_processes(&self) -> std::io::Result<()> {
        let kill_fd = self.open_subtree(std::path::Path::new("cgroup.kill"), Access::Write)?;
        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);
        assert_eq!(rustix::io::write(kill_fd.as_fd(), b"1")?, 1, "kernel bug");
        let mut fds = libc::pollfd {
            fd: poll_fd,
            events: libc::POLLIN | libc::POLLPRI | libc::POLLRDHUP,
            revents: 0,
        };
        // SAFETY: FFI call, valid arguments, fds contains 1 element
        let mut v = vec![];
        'a: loop {
            v.clear();
            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");
            for substr in v.split(|&c| c == b'\n') {
                if substr == b"populated 0" {
                    break 'a;
                }
            }
        }
        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 | ResolveFlags::BENEATH | ResolveFlags::NO_XDEV,
            ResolveFlags::NO_SYMLINKS,
        )?;
        Ok(Self {
            fd,
            path: p.to_owned(),
        })
    }
    pub(crate) fn make_child(&self, p: &Path) -> Result<(), Errno> {
        rustix::fs::mkdirat(
            self.fd.as_fd(),
            p,
            Mode::RUSR
                | Mode::WUSR
                | Mode::XUSR
                | Mode::RGRP
                | Mode::XGRP
                | Mode::ROTH
                | Mode::XOTH,
        )
    }

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

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 cd77becc0b40bfdcd983e53b63b7c21e4308d5fc ...
found cd77becc0b40bfdcd983e53b63b7c21e4308d5fc in https://inbox.spectrum-os.org/spectrum-devel/20260620-cgroups-v2-1-ccae224b6c85@gmail.com/

applying [1/1] https://inbox.spectrum-os.org/spectrum-devel/20260620-cgroups-v2-1-ccae224b6c85@gmail.com/
diff --git a/tools/cgroup-setup/src/cgroup.rs b/tools/cgroup-setup/src/cgroup.rs
new file mode 100644
index 0000000000000000000000000000000000000000..cd77becc0b40bfdcd983e53b63b7c21e4308d5fc

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

index at:
100644 cd77becc0b40bfdcd983e53b63b7c21e4308d5fc	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/crosvm
	https://spectrum-os.org/git/doc
	https://spectrum-os.org/git/mktuntap
	https://spectrum-os.org/git/nixpkgs
	https://spectrum-os.org/git/spectrum
	https://spectrum-os.org/git/ucspi-vsock
	https://spectrum-os.org/git/www

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).