Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/libcgroups/examples/systemd_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ fn main() -> Result<()> {
disable_oom_killer: false,
oom_score_adj: None,
freezer_state: None,
skip_devices: false,
};

let pid = Pid::from_raw(std::process::id() as i32);
Expand Down
3 changes: 3 additions & 0 deletions crates/libcgroups/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@ pub struct ControllerOpt<'a> {
pub oom_score_adj: Option<i32>,
/// FreezerState is given to freezer controller for suspending process.
pub freezer_state: Option<FreezerState>,
/// Skips the devices controller, so the container keeps the device rules it has.
/// Set by the update path, following runc's SkipDevices.
pub skip_devices: bool,
}

#[derive(thiserror::Error, Debug)]
Expand Down
32 changes: 32 additions & 0 deletions crates/libcgroups/src/systemd/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ impl Devices {
systemd_version: u32,
properties: &mut HashMap<&str, Variant>,
) -> Result<(), SystemdDevicesError> {
if options.skip_devices {
return Ok(());
}

// An absent rule list is not a request for unrestricted access, and the cgroupfs
// path (v2::devices::controller) does not read it as one either.
let devices = options.resources.devices().as_deref().unwrap_or_default();
Expand Down Expand Up @@ -325,6 +329,7 @@ Block devices:
freezer_state: None,
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: false,
};
let mut props: HashMap<&str, Variant> = HashMap::new();
Devices::apply_devices_from(proc_devices, &opt, systemd_version, &mut props)?;
Expand Down Expand Up @@ -375,6 +380,33 @@ Block devices:
);
}

#[test]
fn test_skip_devices_writes_no_device_properties() {
// An update must leave the unit's device properties alone, so systemd keeps
// deriving its filter from the rules the container was created with.
let rule = LinuxDeviceCgroupBuilder::default()
.typ(LinuxDeviceType::A)
.allow(true)
.build()
.unwrap();
let resources = resources(vec![rule]);
let mut props: HashMap<&str, Variant> = HashMap::new();
let opt = ControllerOpt {
resources: &resources,
freezer_state: None,
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: true,
};

Devices::apply_devices_from(PROC_DEVICES, &opt, 245, &mut props).unwrap();

assert!(
!props.contains_key("DevicePolicy") && !props.contains_key("DeviceAllow"),
"a skipped update must not send device properties, got {props:?}"
);
}

#[test]
fn test_allow_all_sets_auto_policy() {
let rule = LinuxDeviceCgroupBuilder::default()
Expand Down
105 changes: 84 additions & 21 deletions crates/libcgroups/src/systemd/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,12 +511,74 @@ impl CgroupManager for Manager {
tracing::debug!("applying properties {:?}", properties);
Unified::apply(controller_opt, systemd_version, &mut properties)?;

if !properties.is_empty() {
self.ensure_controllers_attached()?;
// Enable the controllers systemd does not enable itself (hugetlb, misc,
// rdma) down to the unit, as every apply did before the skip existed: an
// update that sends no unit property but writes unified keys still needs
// the files. Before the skip, the device properties kept this list
// non-empty, so this ran for every apply.
self.ensure_controllers_attached()?;

// Setting unit properties makes systemd attach the device filter it derives
// from the unit's DeviceAllow, even when no device property is sent. For rules
// that keep a deny, youki created the unit with an empty DeviceAllow and a
// strict policy, so that filter denies every device. A skipped update sends
// properties without device rules, so it lists the attached programs before
// the call and detaches the ones that appeared during it. youki's own program,
// attached at create, stays and keeps enforcing the container's rules.
#[cfg(feature = "cgroupsv2_devices")]
let attached_before = if controller_opt.skip_devices && !properties.is_empty() {
match crate::v2::devices::Devices::attached_program_ids(&self.full_path) {
Ok(ids) => Some(ids),
// A rootless update cannot list the programs; like the rest of the
// device handling there, this is best effort.
Err(err) if self.rootless => {
tracing::warn!(
"rootless cgroup: cannot list the attached device programs for \
{:?}: {err}; leaving the filters alone",
self.full_path
);
None
}
Err(err) => return Err(err.into()),
}
} else {
None
};

let set_result = if !properties.is_empty() {
self.client
.set_unit_properties(&self.unit_name, &properties)?;
.set_unit_properties(&self.unit_name, &properties)
} else {
Ok(())
};

// This runs before the cgroupfs writes below and also when the property call
// failed, since systemd may have applied the properties anyway.
#[cfg(feature = "cgroupsv2_devices")]
if let Some(before) = attached_before {
match crate::v2::devices::Devices::detach_programs_added(&self.full_path, &before) {
Ok(_) => {}
// Like runc, treat device rules as best effort in rootless mode instead of
// failing the container.
Err(err) if self.rootless => {
tracing::warn!(
"rootless cgroup: cannot detach the device programs added for {:?}: {err}",
self.full_path
);
}
// The property call failed too; its error is the one returned.
Err(err) if set_result.is_err() => {
tracing::warn!(
"could not detach the device programs added for {:?}: {err}",
self.full_path
);
}
Err(err) => return Err(err.into()),
}
}

set_result?;

// Only some unified keys map to a unit property, so write all of them to the cgroup
// as well, as runc does. Keys systemd has just set get the same value again.
crate::v2::unified::Unified::apply(
Expand All @@ -526,26 +588,27 @@ impl CgroupManager for Manager {
.map_err(V2ManagerError::from)?,
)?;

// systemd derives a device filter from DeviceAllow and attaches it every time
// unit properties are set, so this has to run afterwards to replace it. A rule
// DeviceAllow cannot express, a deny rule above all, is only honoured by the
// program built here.
// A rule DeviceAllow cannot express, a deny rule above all, is only honoured by
// the program built here, which replaces the filter systemd derives from the
// properties above. A skipped update built no program, so it attaches none.
#[cfg(feature = "cgroupsv2_devices")]
match crate::v2::devices::Devices::apply_devices(
&self.full_path,
controller_opt.resources.devices(),
) {
Ok(()) => {}
// Like runc, treat device rules as best effort in rootless mode instead of
// failing the container.
Err(err) if self.rootless => {
tracing::warn!(
"rootless cgroup: cannot apply device rules to {:?}: {err}; \
skipping device cgroup",
self.full_path
);
if !controller_opt.skip_devices {
match crate::v2::devices::Devices::apply_devices(
&self.full_path,
controller_opt.resources.devices(),
) {
Ok(()) => {}
// Like runc, treat device rules as best effort in rootless mode instead of
// failing the container.
Err(err) if self.rootless => {
tracing::warn!(
"rootless cgroup: cannot apply device rules to {:?}: {err}; \
skipping device cgroup",
self.full_path
);
}
Err(err) => return Err(err.into()),
}
Err(err) => return Err(err.into()),
}

Ok(())
Expand Down
1 change: 1 addition & 0 deletions crates/libcgroups/src/systemd/pids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ mod tests {
disable_oom_killer: false,
oom_score_adj: None,
freezer_state: None,
skip_devices: false,
};

(options, properties)
Expand Down
28 changes: 25 additions & 3 deletions crates/libcgroups/src/v1/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,14 @@ impl Controller for Devices {
Ok(())
}

// always needs to be called due to default devices
fn needs_to_handle<'a>(_controller_opt: &'a ControllerOpt) -> Option<&'a Self::Resource> {
// An update skips the device rules, so it does not select this controller and
// does not need the devices hierarchy either.
fn needs_to_handle<'a>(controller_opt: &'a ControllerOpt) -> Option<&'a Self::Resource> {
if controller_opt.skip_devices {
return None;
}

// always needs to be called due to default devices
Some(&())
}
}
Expand All @@ -55,7 +61,7 @@ impl Devices {
mod tests {
use std::fs::read_to_string;

use oci_spec::runtime::{LinuxDeviceCgroupBuilder, LinuxDeviceType};
use oci_spec::runtime::{LinuxDeviceCgroupBuilder, LinuxDeviceType, LinuxResourcesBuilder};

use super::*;
use crate::test::set_fixture;
Expand Down Expand Up @@ -138,6 +144,22 @@ mod tests {
});
}

#[test]
fn test_skip_devices_deselects_the_controller() {
let resources = LinuxResourcesBuilder::default().build().unwrap();
let mut controller_opt = ControllerOpt {
resources: &resources,
freezer_state: None,
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: false,
};
assert!(Devices::needs_to_handle(&controller_opt).is_some());

controller_opt.skip_devices = true;
assert!(Devices::needs_to_handle(&controller_opt).is_none());
}

quickcheck! {
fn property_test_apply_device(device: LinuxDeviceCgroup) -> bool {
let tmp = tempfile::tempdir().unwrap();
Expand Down
3 changes: 3 additions & 0 deletions crates/libcgroups/src/v1/freezer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ mod tests {
freezer_state: Some(state),
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: false,
};

let pid = Pid::from_raw(1000);
Expand Down Expand Up @@ -222,6 +223,7 @@ mod tests {
freezer_state: Some(state),
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: false,
};

let pid = Pid::from_raw(1001);
Expand Down Expand Up @@ -250,6 +252,7 @@ mod tests {
freezer_state: Some(state),
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: false,
};

let pid = Pid::from_raw(1002);
Expand Down
1 change: 1 addition & 0 deletions crates/libcgroups/src/v1/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ impl CgroupManager for Manager {
freezer_state: Some(state),
oom_score_adj: None,
disable_oom_killer: false,
skip_devices: false,
};
Ok(Freezer::apply(
&controller_opt,
Expand Down
1 change: 1 addition & 0 deletions crates/libcgroups/src/v1/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ mod tests {
disable_oom_killer,
oom_score_adj: None,
freezer_state: None,
skip_devices: false,
};

let result = <Memory as Controller>::apply(&controller_opt, tmp.path());
Expand Down
45 changes: 31 additions & 14 deletions crates/libcgroups/src/v2/devices/bpf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,27 @@ pub mod prog {

/// Given a fd for a cgroup, collect the programs associated with it
pub fn query(cgroup_fd: RawFd) -> Result<Vec<ProgramInfo>, super::BpfError> {
let prog_ids = query_ids(cgroup_fd)?;

let mut prog_fds = Vec::with_capacity(prog_ids.len());
for prog_id in &prog_ids {
// collect fds for programs by getting their ids
#[allow(unused_unsafe)]
let prog_fd = unsafe { bpf_prog_get_fd_by_id(*prog_id) };
if prog_fd < 0 {
tracing::debug!("bpf_prog_get_fd_by_id failed: {}", errno::errno());
continue;
}
prog_fds.push(ProgramInfo {
id: *prog_id,
fd: prog_fd,
});
}
Ok(prog_fds)
}

/// Ids of the programs attached to a cgroup, without opening them
pub fn query_ids(cgroup_fd: RawFd) -> Result<Vec<u32>, super::BpfError> {
let mut prog_ids: Vec<u32> = vec![0_u32; 64];
let mut attach_flags = 0_u32;
for _ in 0..10 {
Expand Down Expand Up @@ -100,21 +121,17 @@ pub mod prog {
break;
}

let mut prog_fds = Vec::with_capacity(prog_ids.len());
for prog_id in &prog_ids {
// collect fds for programs by getting their ids
#[allow(unused_unsafe)]
let prog_fd = unsafe { bpf_prog_get_fd_by_id(*prog_id) };
if prog_fd < 0 {
tracing::debug!("bpf_prog_get_fd_by_id failed: {}", errno::errno());
continue;
}
prog_fds.push(ProgramInfo {
id: *prog_id,
fd: prog_fd,
});
Ok(prog_ids)
}

/// Opens a program by id
pub fn get_fd_by_id(prog_id: u32) -> Result<RawFd, super::BpfError> {
#[allow(unused_unsafe)]
let prog_fd = unsafe { bpf_prog_get_fd_by_id(prog_id) };
if prog_fd < 0 {
return Err(errno::errno().into());
}
Ok(prog_fds)
Ok(prog_fd)
}

pub fn detach2(prog_fd: RawFd, cgroup_fd: RawFd) -> Result<(), super::BpfError> {
Expand Down
Loading
Loading