From ce5f5f638e59c1f41345d2ab00798b215e50ea91 Mon Sep 17 00:00:00 2001 From: mengze Date: Mon, 23 Oct 2023 17:34:51 +0800 Subject: [PATCH] Support setting max memory limit in cgroup v2 When setting memory.max/memory.swap.max in cgroup v2, Linux uses "max" instead of "-1" to indicate no restriction on memory usage. The set_limit and set_memswap_limit functions of the memory controller accept i64 as a parameter. In cgroupv2, if the parameter is -1, "max" should be written into the cgroup file. Fixes #128 Signed-off-by: mengze --- src/memory.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/memory.rs b/src/memory.rs index 55477f7..cac5cac 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -844,13 +844,16 @@ impl MemController { /// Set the memory usage limit of the control group, in bytes. pub fn set_limit(&self, limit: i64) -> Result<()> { let mut file_name = "memory.limit_in_bytes"; + let mut limit_str = limit.to_string(); if self.v2 { file_name = "memory.max"; + if limit == -1 { + limit_str = "max".to_string(); + } } self.open_path(file_name, true).and_then(|mut file| { - file.write_all(limit.to_string().as_ref()).map_err(|e| { - Error::with_cause(WriteFailed(file_name.to_string(), limit.to_string()), e) - }) + file.write_all(limit_str.as_ref()) + .map_err(|e| Error::with_cause(WriteFailed(file_name.to_string(), limit_str), e)) }) } @@ -881,13 +884,16 @@ impl MemController { /// Set the memory+swap limit of the control group, in bytes. pub fn set_memswap_limit(&self, limit: i64) -> Result<()> { let mut file_name = "memory.memsw.limit_in_bytes"; + let mut limit_str = limit.to_string(); if self.v2 { file_name = "memory.swap.max"; + if limit == -1 { + limit_str = "max".to_string(); + } } self.open_path(file_name, true).and_then(|mut file| { - file.write_all(limit.to_string().as_ref()).map_err(|e| { - Error::with_cause(WriteFailed(file_name.to_string(), limit.to_string()), e) - }) + file.write_all(limit_str.as_ref()) + .map_err(|e| Error::with_cause(WriteFailed(file_name.to_string(), limit_str), e)) }) }