Skip to main content

rw_resource_util/
lib.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/// Returns the hostname of the current machine, or an empty string if failed,
16/// which rarely happens.
17pub fn hostname() -> String {
18    hostname::get()
19        .unwrap_or_default()
20        .into_string()
21        .unwrap_or_default()
22}
23
24#[derive(Debug, Clone, Copy)]
25pub enum CgroupVersion {
26    V1,
27    V2,
28}
29
30/// Current controllers available in implementation.
31pub enum Controller {
32    Cpu,
33    Memory,
34}
35
36/// Default constant Cgroup paths and hierarchy.
37const DEFAULT_CGROUP_ROOT_HIERARCYHY: &str = "/sys/fs/cgroup";
38const DEFAULT_CGROUP_V2_CONTROLLER_LIST_PATH: &str = "/sys/fs/cgroup/cgroup.controllers";
39const DEFAULT_CGROUP_MAX_INDICATOR: &str = "max";
40
41mod runtime {
42    use std::env;
43    use std::path::Path;
44
45    use thiserror_ext::AsReport;
46
47    use super::CgroupVersion;
48    use super::util::parse_controller_enable_file_for_cgroup_v2;
49    const DEFAULT_DOCKER_ENV_PATH: &str = "/.dockerenv";
50    const DEFAULT_LINUX_IDENTIFIER: &str = "linux";
51    const DEFAULT_IN_CONTAINER_ENV_VARIABLE: &str = "IN_CONTAINER";
52    const DEFAULT_KUBERNETES_SECRETS_PATH: &str = "/var/run/secrets/kubernetes.io";
53
54    fn is_linux_machine() -> bool {
55        env::consts::OS.eq(DEFAULT_LINUX_IDENTIFIER)
56    }
57
58    /// checks if is running in a docker container by checking for docker env file, or if it is
59    /// running in a kubernetes pod.
60    fn is_running_in_container() -> bool {
61        return env_var_check_if_running_in_container()
62            || docker_env_exists()
63            || is_running_in_kubernetes_pod();
64
65        /// checks for existence of docker env file
66        fn docker_env_exists() -> bool {
67            Path::new(DEFAULT_DOCKER_ENV_PATH).exists()
68        }
69
70        /// checks for environment
71        fn env_var_check_if_running_in_container() -> bool {
72            env::var(DEFAULT_IN_CONTAINER_ENV_VARIABLE).is_ok()
73        }
74
75        /// checks if it is running in a kubernetes pod
76        fn is_running_in_kubernetes_pod() -> bool {
77            Path::new(DEFAULT_KUBERNETES_SECRETS_PATH).exists()
78        }
79    }
80
81    /// Given a certain controller, checks if it is enabled.
82    /// For cgroup v1, existence of directory with controller name is checked in cgroup default root
83    /// hierarchy. e.g if directory "/sys/fs/cgroup"/cpu" exists then CPU controller is enabled.
84    /// For cgroup v2, check the controller list path for the controller name.
85    pub fn is_controller_activated(
86        controller_type: super::Controller,
87        cgroup_version: CgroupVersion,
88    ) -> bool {
89        let controller_name: &str = match controller_type {
90            super::Controller::Cpu => "cpu",
91            super::Controller::Memory => "memory",
92        };
93        match cgroup_version {
94            super::CgroupVersion::V1 => Path::new(super::DEFAULT_CGROUP_ROOT_HIERARCYHY)
95                .join(controller_name)
96                .is_dir(),
97            super::CgroupVersion::V2 => parse_controller_enable_file_for_cgroup_v2(
98                super::DEFAULT_CGROUP_V2_CONTROLLER_LIST_PATH,
99                controller_name,
100            ),
101        }
102    }
103
104    /// If cgroup exists or is enabled in kernel, returnb true, else false.
105    fn cgroup_exists() -> bool {
106        Path::new(super::DEFAULT_CGROUP_ROOT_HIERARCYHY).is_dir()
107    }
108
109    pub fn get_resource<T>(
110        desc: &str,
111        controller_type: super::Controller,
112        get_system: fn() -> T,
113        get_container: fn(CgroupVersion) -> Result<T, std::io::Error>,
114    ) -> T {
115        if !is_linux_machine() || !is_running_in_container() || !cgroup_exists() {
116            return get_system();
117        };
118
119        // if cgroup.controllers exist, v2 is used.
120        let cgroup_version = if Path::new(super::DEFAULT_CGROUP_V2_CONTROLLER_LIST_PATH).exists() {
121            super::CgroupVersion::V2
122        } else {
123            super::CgroupVersion::V1
124        };
125        if !is_controller_activated(controller_type, cgroup_version) {
126            return get_system();
127        }
128
129        match get_container(cgroup_version) {
130            Ok(value) => value,
131            Err(err) => {
132                tracing::warn!(
133                    error = %err.as_report(),
134                    cgroup_version = ?cgroup_version,
135                    "failed to get {desc} in container, use system value instead"
136                );
137                get_system()
138            }
139        }
140    }
141}
142
143pub mod memory {
144    use sysinfo::System;
145
146    use super::runtime::get_resource;
147
148    /// Default paths for memory limitations and usage for cgroup v1 and cgroup v2.
149    const V1_MEMORY_LIMIT_PATH: &str = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
150    const V1_MEMORY_CURRENT_PATH: &str = "/sys/fs/cgroup/memory/memory.usage_in_bytes";
151    const V2_MEMORY_LIMIT_PATH: &str = "/sys/fs/cgroup/memory.max";
152    const V2_MEMORY_CURRENT_PATH: &str = "/sys/fs/cgroup/memory.current";
153
154    fn system_with_memory() -> System {
155        // A zero total would invalidate memory sizing, so fail if sysinfo cannot initialize.
156        let mut sys = System::new().expect("failed to initialize system memory information");
157        sys.refresh_memory();
158        sys
159    }
160
161    /// Returns the system memory.
162    pub fn get_system_memory() -> usize {
163        system_with_memory().total_memory() as usize
164    }
165
166    /// Returns the used memory of the system.
167    pub fn get_system_memory_used() -> usize {
168        system_with_memory().used_memory() as usize
169    }
170
171    /// Returns the total memory used in bytes.
172    ///
173    /// In a container, this returns the cgroup's memory usage, including memory charged for
174    /// file cache. If the cgroup usage is unavailable or invalid, this returns the host's
175    /// used memory instead. The cgroup mount point is assumed to be at /sys/fs/cgroup.
176    ///
177    ///
178    /// # Examples
179    ///
180    /// Basic usage:
181    /// ``` ignore
182    /// let mem_used = memory::total_memory_used_bytes();
183    /// ```
184    pub fn total_memory_used_bytes() -> usize {
185        get_resource(
186            "memory used",
187            super::Controller::Memory,
188            get_system_memory_used,
189            |cgroup_version| {
190                let usage_path = match cgroup_version {
191                    super::CgroupVersion::V1 => V1_MEMORY_CURRENT_PATH,
192                    super::CgroupVersion::V2 => V2_MEMORY_CURRENT_PATH,
193                };
194                get_container_memory_used(usage_path)
195            },
196        )
197    }
198
199    /// Returns the total memory available by the system in bytes.
200    ///
201    /// If running in container, this function will read the cgroup interface files for the
202    /// memory available/limit, if interface files are not found, will return the system memory
203    /// volume by default. The cgroup mount point is assumed to be at /sys/fs/cgroup by default.
204    ///
205    ///
206    /// # Examples
207    ///
208    /// Basic usage:
209    /// ``` ignore
210    /// let mem_available = memory::system_memory_available_bytes();
211    /// ```
212    pub fn system_memory_available_bytes() -> usize {
213        get_resource(
214            "memory available",
215            super::Controller::Memory,
216            get_system_memory,
217            get_container_memory_limit,
218        )
219    }
220
221    /// Returns the memory limit of a container if running in a container else returns the system
222    /// memory available.
223    /// When the limit is set to max, [`system_memory_available_bytes()`] will return default system
224    /// memory.
225    fn get_container_memory_limit(
226        cgroup_version: super::CgroupVersion,
227    ) -> Result<usize, std::io::Error> {
228        let limit_path = match cgroup_version {
229            super::CgroupVersion::V1 => V1_MEMORY_LIMIT_PATH,
230            super::CgroupVersion::V2 => V2_MEMORY_LIMIT_PATH,
231        };
232        let system = get_system_memory();
233        let value = super::util::read_usize_or_max(limit_path, system)?;
234        Ok(std::cmp::min(value, system))
235    }
236
237    fn get_container_memory_used(usage_path: &str) -> Result<usize, std::io::Error> {
238        // Host used memory can exclude reclaimable cache charged to the cgroup.
239        super::util::read_usize(usage_path)
240    }
241
242    #[cfg(test)]
243    mod tests {
244        use std::io::ErrorKind;
245
246        use super::get_container_memory_used;
247
248        #[test]
249        fn test_container_memory_usage() {
250            let dir = tempfile::tempdir().unwrap();
251            let usage_path = dir.path().join("memory.current");
252            let path = usage_path.to_str().unwrap();
253
254            // An intentionally large counter must be returned without a host-dependent cap.
255            std::fs::write(&usage_path, format!("{}\n", usize::MAX)).unwrap();
256            assert_eq!(get_container_memory_used(path).unwrap(), usize::MAX);
257
258            std::fs::write(&usage_path, "max\n").unwrap();
259            assert_eq!(
260                get_container_memory_used(path).unwrap_err().kind(),
261                ErrorKind::InvalidData
262            );
263            std::fs::remove_file(&usage_path).unwrap();
264            assert_eq!(
265                get_container_memory_used(path).unwrap_err().kind(),
266                ErrorKind::NotFound
267            );
268        }
269    }
270}
271
272pub mod cpu {
273    use std::thread;
274
275    use thiserror_ext::AsReport;
276
277    use super::runtime::get_resource;
278    use super::util::parse_error;
279
280    /// Default constant Cgroup paths and hierarchy.
281    const V1_CPU_QUOTA_PATH: &str = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
282    const V1_CPU_PERIOD_PATH: &str = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
283    const V2_CPU_LIMIT_PATH: &str = "/sys/fs/cgroup/cpu.max";
284
285    /// Returns the total number of cpu available as a float.
286    ///
287    /// If running in container, this function will return the cpu limit by the container. If not,
288    /// it will return the ```available_parallelism``` by the system. A panic will be invoked if
289    /// invoking process does not have permission to read appropriate values by
290    /// ```std::thread::available_parallelism``` or if the platform is not supported. The cgroup
291    /// mount point is assumed to be at /sys/fs/cgroup by default.
292    ///
293    ///
294    /// # Examples
295    ///
296    /// Basic usage:
297    /// ``` ignore
298    /// let cpu_available = cpu::total_cpu_available();
299    /// ```
300    pub fn total_cpu_available() -> f32 {
301        get_resource(
302            "cpu quota",
303            super::Controller::Cpu,
304            get_system_cpu,
305            get_container_cpu_limit,
306        )
307    }
308
309    /// Returns the CPU limit of the container.
310    fn get_container_cpu_limit(
311        cgroup_version: super::CgroupVersion,
312    ) -> Result<f32, std::io::Error> {
313        let max_cpu = get_system_cpu();
314        match cgroup_version {
315            super::CgroupVersion::V1 => {
316                get_cpu_limit_v1(V1_CPU_QUOTA_PATH, V1_CPU_PERIOD_PATH, max_cpu)
317            }
318            super::CgroupVersion::V2 => get_cpu_limit_v2(V2_CPU_LIMIT_PATH, max_cpu),
319        }
320    }
321
322    /// Returns the total system cpu.
323    pub fn get_system_cpu() -> f32 {
324        match thread::available_parallelism() {
325            Ok(available_parallelism) => available_parallelism.get() as f32,
326            Err(e) => panic!(
327                "Failed to get available parallelism, error: {}",
328                e.as_report()
329            ),
330        }
331    }
332
333    /// Returns the CPU limit when cgroup v1 is utilised.
334    pub fn get_cpu_limit_v1(
335        quota_path: &str,
336        period_path: &str,
337        max_value: f32,
338    ) -> Result<f32, std::io::Error> {
339        let content = std::fs::read_to_string(quota_path)?;
340        let cpu_quota = content
341            .trim()
342            .parse::<i64>()
343            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "not a number"))?;
344        // According to the kernel documentation, if the value is negative, it means no limit.
345        // https://docs.kernel.org/scheduler/sched-bwc.html#management
346        if cpu_quota < 0 {
347            return Ok(max_value);
348        }
349
350        let cpu_period = super::util::read_usize(period_path)?;
351
352        Ok((cpu_quota as f32) / (cpu_period as f32))
353    }
354
355    /// Returns the CPU limit when cgroup v2 is utilised.
356    pub fn get_cpu_limit_v2(limit_path: &str, max_value: f32) -> Result<f32, std::io::Error> {
357        let cpu_limit_string = fs_err::read_to_string(limit_path)?;
358
359        let cpu_data: Vec<&str> = cpu_limit_string.split_whitespace().collect();
360        match cpu_data.get(0..2) {
361            Some(cpu_data_values) => {
362                if cpu_data_values[0] == super::DEFAULT_CGROUP_MAX_INDICATOR {
363                    return Ok(max_value);
364                }
365                let cpu_quota = cpu_data_values[0]
366                    .parse::<usize>()
367                    .map_err(|e| parse_error(limit_path, &cpu_limit_string, e))?;
368                let cpu_period = cpu_data_values[1]
369                    .parse::<usize>()
370                    .map_err(|e| parse_error(limit_path, &cpu_limit_string, e))?;
371                Ok((cpu_quota as f32) / (cpu_period as f32))
372            }
373            None => Err(std::io::Error::new(
374                std::io::ErrorKind::InvalidData,
375                format!(
376                    "Invalid format in Cgroup CPU interface file, path: {limit_path}, content: {cpu_limit_string}"
377                ),
378            )),
379        }
380    }
381}
382
383mod util {
384    /// Parses the filepath and checks for the existence of `controller_name` in the file.
385    pub fn parse_controller_enable_file_for_cgroup_v2(
386        file_path: &str,
387        controller_name: &str,
388    ) -> bool {
389        match fs_err::read_to_string(file_path) {
390            Ok(controller_string) => {
391                for controller in controller_string.split_whitespace() {
392                    if controller.eq(controller_name) {
393                        return true;
394                    };
395                }
396                false
397            }
398            Err(_) => false,
399        }
400    }
401
402    pub fn parse_error(
403        file_path: &str,
404        content: &str,
405        e: impl std::fmt::Display,
406    ) -> std::io::Error {
407        std::io::Error::new(
408            std::io::ErrorKind::InvalidData,
409            format!("failed to parse, path: {file_path}, content: {content}, error: {e}"),
410        )
411    }
412
413    /// Reads an integer value from a file path.
414    pub fn read_usize(file_path: &str) -> Result<usize, std::io::Error> {
415        let content = fs_err::read_to_string(file_path)?;
416        let limit_val = content
417            .trim()
418            .parse::<usize>()
419            .map_err(|e| parse_error(file_path, &content, e))?;
420        Ok(limit_val)
421    }
422
423    /// Helper function that helps to retrieve value in file, if value is "max", `max_value` will be
424    /// returned instead.
425    pub fn read_usize_or_max(file_path: &str, max_value: usize) -> Result<usize, std::io::Error> {
426        let content = fs_err::read_to_string(file_path)?;
427        if content.trim() == super::DEFAULT_CGROUP_MAX_INDICATOR {
428            return Ok(max_value);
429        }
430        let limit_val = content
431            .trim()
432            .parse::<usize>()
433            .map_err(|e| parse_error(file_path, &content, e))?;
434        Ok(limit_val)
435    }
436
437    #[cfg(test)]
438    mod tests {
439        use std::collections::HashMap;
440        use std::io::prelude::*;
441        use std::thread;
442
443        use super::*;
444        use crate::cpu::{self, get_system_cpu};
445        use crate::memory::get_system_memory;
446        use crate::{Controller, DEFAULT_CGROUP_MAX_INDICATOR};
447        const DEFAULT_NON_EXISTENT_PATH: &str = "default-non-existent-path";
448
449        #[test]
450        fn test_read_integer_from_file_path() {
451            struct TestCase {
452                file_exists: bool,
453                value_in_file: String,
454                expected: Result<usize, std::io::Error>,
455            }
456
457            let test_cases = HashMap::from([
458                (
459                    "valid-integer-value-in-file",
460                    TestCase {
461                        file_exists: true,
462                        value_in_file: String::from("10000"),
463                        expected: Ok(10000),
464                    },
465                ),
466                (
467                    "valid-integer-value-in-file-with-spaces-after",
468                    TestCase {
469                        file_exists: true,
470                        value_in_file: String::from("10000   "),
471                        expected: Ok(10000),
472                    },
473                ),
474                (
475                    "valid-integer-value-in-file-with-spaces-before",
476                    TestCase {
477                        file_exists: true,
478                        value_in_file: String::from("   10000"),
479                        expected: Ok(10000),
480                    },
481                ),
482                (
483                    "invalid-integer-value-in-file",
484                    TestCase {
485                        file_exists: true,
486                        value_in_file: String::from("test-string"),
487                        expected: Err(std::io::Error::new(
488                            std::io::ErrorKind::InvalidData,
489                            "not a number",
490                        )),
491                    },
492                ),
493                (
494                    "file-not-exist",
495                    TestCase {
496                        file_exists: false,
497                        value_in_file: String::from(""),
498                        expected: Err(std::io::Error::new(
499                            std::io::ErrorKind::NotFound,
500                            "File not found",
501                        )),
502                    },
503                ),
504                (
505                    "max-value-in-file",
506                    TestCase {
507                        file_exists: true,
508                        value_in_file: String::from(DEFAULT_CGROUP_MAX_INDICATOR),
509                        expected: Err(std::io::Error::new(
510                            std::io::ErrorKind::InvalidData,
511                            "not a number",
512                        )),
513                    },
514                ),
515            ]);
516
517            for tc in test_cases {
518                let curr_test_case = &tc.1;
519                let mut file: tempfile::NamedTempFile;
520                let mut test_file_path = String::from(DEFAULT_NON_EXISTENT_PATH);
521                if curr_test_case.file_exists {
522                    file = tempfile::NamedTempFile::new()
523                        .expect("Error encountered while creating file!");
524                    file.as_file_mut()
525                        .write_all(curr_test_case.value_in_file.as_bytes())
526                        .expect("Error while writing to file");
527                    test_file_path = String::from(file.path().to_str().unwrap())
528                }
529                match read_usize(&test_file_path) {
530                    Ok(int_val) => assert_eq!(&int_val, curr_test_case.expected.as_ref().unwrap()),
531                    Err(e) => assert_eq!(
532                        e.kind(),
533                        curr_test_case.expected.as_ref().unwrap_err().kind()
534                    ),
535                }
536            }
537        }
538
539        #[test]
540        fn test_get_value_from_file() {
541            struct TestCase {
542                file_exists: bool,
543                value_in_file: String,
544                expected: Result<usize, std::io::Error>,
545            }
546
547            let test_cases = HashMap::from([
548                (
549                    "valid-integer-value-in-file",
550                    TestCase {
551                        file_exists: true,
552                        value_in_file: String::from("10000"),
553                        expected: Ok(10000),
554                    },
555                ),
556                (
557                    "valid-integer-value-in-file-with-spaces-after",
558                    TestCase {
559                        file_exists: true,
560                        value_in_file: String::from("10000   "),
561                        expected: Ok(10000),
562                    },
563                ),
564                (
565                    "valid-integer-value-in-file-with-spaces-before",
566                    TestCase {
567                        file_exists: true,
568                        value_in_file: String::from("   10000"),
569                        expected: Ok(10000),
570                    },
571                ),
572                (
573                    "invalid-integer-value-in-file",
574                    TestCase {
575                        file_exists: true,
576                        value_in_file: String::from("test-string"),
577                        expected: Err(std::io::Error::new(
578                            std::io::ErrorKind::InvalidData,
579                            "not a number",
580                        )),
581                    },
582                ),
583                (
584                    "file-not-exist",
585                    TestCase {
586                        file_exists: false,
587                        value_in_file: String::from(""),
588                        expected: Err(std::io::Error::new(
589                            std::io::ErrorKind::NotFound,
590                            "File not found",
591                        )),
592                    },
593                ),
594                (
595                    "max-value-in-file",
596                    TestCase {
597                        file_exists: true,
598                        value_in_file: String::from(DEFAULT_CGROUP_MAX_INDICATOR),
599                        expected: Ok(get_system_memory()),
600                    },
601                ),
602            ]);
603
604            for tc in test_cases {
605                let curr_test_case = &tc.1;
606                let mut file: tempfile::NamedTempFile;
607                let mut test_file_path = String::from(DEFAULT_NON_EXISTENT_PATH);
608                if curr_test_case.file_exists {
609                    file = tempfile::NamedTempFile::new()
610                        .expect("Error encountered while creating file!");
611                    file.as_file_mut()
612                        .write_all(curr_test_case.value_in_file.as_bytes())
613                        .expect("Error while writing to file");
614                    test_file_path = String::from(file.path().to_str().unwrap())
615                }
616                match read_usize_or_max(&test_file_path, get_system_memory()) {
617                    Ok(int_val) => assert_eq!(&int_val, curr_test_case.expected.as_ref().unwrap()),
618                    Err(e) => assert_eq!(
619                        e.kind(),
620                        curr_test_case.expected.as_ref().unwrap_err().kind()
621                    ),
622                }
623            }
624        }
625
626        #[test]
627        fn test_get_cpu_limit_v1() {
628            #[derive(Debug)]
629            struct TestCase {
630                file_exists: bool,
631                value_in_quota_file: String,
632                value_in_period_file: String,
633                expected: Result<f32, std::io::Error>,
634            }
635
636            let test_cases = HashMap::from([
637                (
638                    "default-values",
639                    TestCase {
640                        file_exists: true,
641                        value_in_quota_file: String::from("-1"),
642                        value_in_period_file: String::from("10000"),
643                        expected: Ok(thread::available_parallelism().unwrap().get() as f32),
644                    },
645                ),
646                (
647                    "valid-values-in-file",
648                    TestCase {
649                        file_exists: true,
650                        value_in_quota_file: String::from("10000"),
651                        value_in_period_file: String::from("20000"),
652                        expected: Ok(10000.0 / 20000.0),
653                    },
654                ),
655                (
656                    "empty-value-in-files",
657                    TestCase {
658                        file_exists: true,
659                        value_in_quota_file: String::from(""),
660                        value_in_period_file: String::from(""),
661                        expected: Err(std::io::Error::new(
662                            std::io::ErrorKind::InvalidData,
663                            "Invalid format in Cgroup CPU interface file",
664                        )),
665                    },
666                ),
667                (
668                    "Invalid-string-value-in-file",
669                    TestCase {
670                        file_exists: true,
671                        value_in_quota_file: String::from("10000"),
672                        value_in_period_file: String::from("test-string "),
673                        expected: Err(std::io::Error::new(
674                            std::io::ErrorKind::InvalidData,
675                            "not a number",
676                        )),
677                    },
678                ),
679                (
680                    "negative-value-in-file",
681                    TestCase {
682                        file_exists: true,
683                        value_in_quota_file: String::from("-2"),
684                        value_in_period_file: String::from("20000"),
685                        expected: Ok(thread::available_parallelism().unwrap().get() as f32),
686                    },
687                ),
688                (
689                    "file-not-exist",
690                    TestCase {
691                        file_exists: false,
692                        value_in_quota_file: String::from("10000 20000"),
693                        value_in_period_file: String::from("10000 20000"),
694                        expected: Err(std::io::Error::new(
695                            std::io::ErrorKind::NotFound,
696                            "File not found",
697                        )),
698                    },
699                ),
700            ]);
701            for tc in test_cases {
702                let curr_test_case = &tc.1;
703                let mut quota_file: tempfile::NamedTempFile;
704                let mut period_file: tempfile::NamedTempFile;
705                let mut test_quota_file_path = String::from(DEFAULT_NON_EXISTENT_PATH);
706                let mut test_period_file_path = String::from(DEFAULT_NON_EXISTENT_PATH);
707                if curr_test_case.file_exists {
708                    quota_file = tempfile::NamedTempFile::new()
709                        .expect("Error encountered while creating file!");
710                    quota_file
711                        .as_file_mut()
712                        .write_all(curr_test_case.value_in_quota_file.as_bytes())
713                        .expect("Error while writing to file");
714                    test_quota_file_path = String::from(quota_file.path().to_str().unwrap());
715
716                    period_file = tempfile::NamedTempFile::new()
717                        .expect("Error encountered while creating file!");
718                    period_file
719                        .as_file_mut()
720                        .write_all(curr_test_case.value_in_period_file.as_bytes())
721                        .expect("Error while writing to file");
722                    test_period_file_path = String::from(period_file.path().to_str().unwrap());
723                }
724                match cpu::get_cpu_limit_v1(
725                    &test_quota_file_path,
726                    &test_period_file_path,
727                    get_system_cpu(),
728                ) {
729                    Ok(int_val) => assert_eq!(
730                        &int_val,
731                        curr_test_case.expected.as_ref().unwrap(),
732                        "{:?}",
733                        tc
734                    ),
735                    Err(e) => assert_eq!(
736                        e.kind(),
737                        curr_test_case.expected.as_ref().unwrap_err().kind()
738                    ),
739                }
740            }
741        }
742
743        #[test]
744        fn test_get_cpu_limit_v2() {
745            struct TestCase {
746                file_exists: bool,
747                value_in_file: String,
748                expected: Result<f32, std::io::Error>,
749            }
750
751            let test_cases = HashMap::from([
752                (
753                    "valid-values-in-file",
754                    TestCase {
755                        file_exists: true,
756                        value_in_file: String::from("10000 20000"),
757                        expected: Ok(10000.0 / 20000.0),
758                    },
759                ),
760                (
761                    "Invalid-single-value-in-file",
762                    TestCase {
763                        file_exists: true,
764                        value_in_file: String::from("10000"),
765                        expected: Err(std::io::Error::new(
766                            std::io::ErrorKind::InvalidData,
767                            "Invalid format in Cgroup CPU interface file",
768                        )),
769                    },
770                ),
771                (
772                    "Invalid-string-value-in-file",
773                    TestCase {
774                        file_exists: true,
775                        value_in_file: String::from("10000 test-string "),
776                        expected: Err(std::io::Error::new(
777                            std::io::ErrorKind::InvalidData,
778                            "not a number",
779                        )),
780                    },
781                ),
782                (
783                    "max-value-in-file",
784                    TestCase {
785                        file_exists: true,
786                        value_in_file: String::from("max 20000"),
787                        expected: Ok(thread::available_parallelism().unwrap().get() as f32),
788                    },
789                ),
790                (
791                    "file-not-exist",
792                    TestCase {
793                        file_exists: false,
794                        value_in_file: String::from(""),
795                        expected: Err(std::io::Error::new(
796                            std::io::ErrorKind::NotFound,
797                            "File not found",
798                        )),
799                    },
800                ),
801            ]);
802            for tc in test_cases {
803                let curr_test_case = &tc.1;
804                let mut file: tempfile::NamedTempFile;
805                let mut test_file_path = String::from(DEFAULT_NON_EXISTENT_PATH);
806                if curr_test_case.file_exists {
807                    file = tempfile::NamedTempFile::new()
808                        .expect("Error encountered while creating file!");
809                    file.as_file_mut()
810                        .write_all(curr_test_case.value_in_file.as_bytes())
811                        .expect("Error while writing to file");
812                    test_file_path = String::from(file.path().to_str().unwrap())
813                }
814                match cpu::get_cpu_limit_v2(&test_file_path, get_system_cpu()) {
815                    Ok(int_val) => assert_eq!(&int_val, curr_test_case.expected.as_ref().unwrap()),
816                    Err(e) => assert_eq!(
817                        e.kind(),
818                        curr_test_case.expected.as_ref().unwrap_err().kind()
819                    ),
820                }
821            }
822        }
823
824        #[test]
825        fn test_parse_controller_enable_file_for_cgroup_v2() {
826            struct TestCase {
827                file_exists: bool,
828                value_in_file: String,
829                controller_type: Controller,
830                expected: bool,
831            }
832
833            let test_cases = HashMap::from([
834                (
835                    "cpu-enabled",
836                    TestCase {
837                        file_exists: true,
838                        value_in_file: String::from("cpu memory IO"),
839                        controller_type: Controller::Cpu,
840                        expected: true,
841                    },
842                ),
843                (
844                    "memory-enabled",
845                    TestCase {
846                        file_exists: true,
847                        value_in_file: String::from("cpu memory IO"),
848                        controller_type: Controller::Memory,
849                        expected: true,
850                    },
851                ),
852                (
853                    "memory-disabled",
854                    TestCase {
855                        file_exists: true,
856                        value_in_file: String::from("cpu IO"),
857                        controller_type: Controller::Memory,
858                        expected: false,
859                    },
860                ),
861                (
862                    "cpu-disabled",
863                    TestCase {
864                        file_exists: true,
865                        value_in_file: String::from("memory IO"),
866                        controller_type: Controller::Cpu,
867                        expected: false,
868                    },
869                ),
870                (
871                    "Invalid-value-in-file",
872                    TestCase {
873                        file_exists: true,
874                        value_in_file: String::from("test-string test-string"),
875                        controller_type: Controller::Cpu,
876                        expected: false,
877                    },
878                ),
879                (
880                    "controller-file-not-exist",
881                    TestCase {
882                        file_exists: false,
883                        value_in_file: String::from(""),
884                        controller_type: Controller::Memory,
885                        expected: false,
886                    },
887                ),
888            ]);
889
890            for tc in test_cases {
891                let curr_test_case = &tc.1;
892                let controller_name: &str = match curr_test_case.controller_type {
893                    Controller::Cpu => "cpu",
894                    Controller::Memory => "memory",
895                };
896                let mut file: tempfile::NamedTempFile;
897                let mut test_file_path = String::from(DEFAULT_NON_EXISTENT_PATH);
898                if curr_test_case.file_exists {
899                    file = tempfile::NamedTempFile::new()
900                        .expect("Error encountered while creating file!");
901                    file.as_file_mut()
902                        .write_all(curr_test_case.value_in_file.as_bytes())
903                        .expect("Error while writing to file");
904                    test_file_path = String::from(file.path().to_str().unwrap())
905                }
906                assert_eq!(
907                    parse_controller_enable_file_for_cgroup_v2(&test_file_path, controller_name),
908                    curr_test_case.expected
909                );
910            }
911        }
912    }
913}