Skip to content

Commit

Permalink
agent: correct CPUShares and CPUWeight value
Browse files Browse the repository at this point in the history
If cgroup driver is systemd, CPUShares, for cgroup v1, should be at
least 2 [1] and CPUWeight for cgroup v2, should be at least 1 [2].

Fixes: #8340
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>

[1] https://github.com/systemd/systemd/blob/d19434fbf81db04d03c8cffa87821f754a86635b/src/basic/cgroup-util.h#L122
[2] https://github.com/systemd/systemd/blob/d19434fbf81db04d03c8cffa87821f754a86635b/src/basic/cgroup-util.h#L91
  • Loading branch information
jongwu committed Dec 14, 2023
1 parent ee74fca commit 58e88d9
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/agent/rustjail/src/cgroups/systemd/subsystem/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
use super::super::common::{CgroupHierarchy, Properties};
use super::transformer::Transformer;

use anyhow::Result;
use anyhow::{bail, Result};
use oci::{LinuxCpu, LinuxResources};
use zbus::zvariant::Value;

const BASIC_SYSTEMD_VERSION: &str = "242";
const DEFAULT_CPUQUOTAPERIOD: u64 = 100 * 1000;
const SEC2MICROSEC: u64 = 1000 * 1000;
const BASIC_INTERVAL: u64 = 10 * 1000;
const CGROUP_CPU_SHARES_MAX: u64 = 262144;

pub struct Cpu {}

Expand Down Expand Up @@ -50,6 +51,12 @@ impl Cpu {
systemd_version: &str,
) -> Result<()> {
if let Some(shares) = cpu_resources.shares {
// Minimum value of CPUShares should be 2, see https://github.com/systemd/systemd/blob/d19434fbf81db04d03c8cffa87821f754a86635b/src/basic/cgroup-util.h#L122
let shares = match shares {
0 => 1024,
2..=CGROUP_CPU_SHARES_MAX => shares,
_ => bail!("Invalid CpuShares"),
};
properties.push(("CPUShares", Value::U64(shares)));
}

Expand Down Expand Up @@ -80,7 +87,7 @@ impl Cpu {
systemd_version: &str,
) -> Result<()> {
if let Some(shares) = cpu_resources.shares {
let weight = shares_to_weight(shares);
let weight = shares_to_weight(shares).unwrap();
properties.push(("CPUWeight", Value::U64(weight)));
}

Expand All @@ -104,12 +111,14 @@ impl Cpu {

// ref: https://github.com/containers/crun/blob/main/crun.1.md#cgroup-v2
// [2-262144] to [1-10000]
fn shares_to_weight(shares: u64) -> u64 {
if shares == 0 {
return 100;
}

1 + ((shares - 2) * 9999) / 262142
fn shares_to_weight(shares: u64) -> Result<u64> {
let weight = match shares {
0 => 100,
1..=CGROUP_CPU_SHARES_MAX => 1 + ((shares - 2) * 9999) / 262142,
_ => bail!("Can't convert CpuShares to CpuWeight: invalid CpuShares"),
};

Ok(weight)
}

fn resolve_cpuquota(quota: i64, period: u64) -> u64 {
Expand Down

0 comments on commit 58e88d9

Please sign in to comment.