Debian Codegraph @

debian/rust-vendor/rlimit/src/sys_limits.rs

raw
1 #![deny(unsafe_code)]
2
3 use std::fs;
4 use std::io;
5 use std::path::Path;
6
7 /// System-wide file descriptor limits and statistics.
8 ///
9 /// These values are read from and written to the **proc** filesystem under `/proc/sys/fs/`.
10 ///
11 /// See <https://www.kernel.org/doc/Documentation/sysctl/fs.txt> and
12 /// <https://man7.org/linux/man-pages/man5/proc.5.html>.
13 ///
14 #[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
15 #[derive(Debug, Clone, Default, PartialEq, Eq)]
16 #[non_exhaustive]
17 pub struct SysLimits {
18 /// System-wide limit on the total number of file descriptors that can be allocated.
19 ///
20 /// This corresponds to `/proc/sys/fs/file-max`.
21 pub file_max: Option<u64>,
22
23 /// Current file descriptor usage statistics.
24 ///
25 /// This corresponds to `/proc/sys/fs/file-nr` and contains three values:
26 /// - `allocated`: Number of allocated file descriptors
27 /// - `free`: Number of free file descriptors (deprecated, always 0 in modern kernels)
28 /// - `maximum`: Maximum number of file descriptors (same as `file_max`)
29 ///
30 /// This field is read-only.
31 pub file_nr: Option<FileNr>,
32
33 /// Per-process maximum number of file descriptors that can be allocated.
34 ///
35 /// This corresponds to `/proc/sys/fs/nr_open`. This is the ceiling value that
36 /// can be set for the per-process NOFILE limit (both hard and soft).
37 pub nr_open: Option<u64>,
38 }
39
40 /// File descriptor usage statistics from `/proc/sys/fs/file-nr`.
41 ///
42 /// **Note:** The "free" field has been deprecated since Linux 2.6 and is always 0 in modern kernels.
43 #[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
44 #[derive(Debug, Clone, Default, PartialEq, Eq)]
45 pub struct FileNr {
46 /// Number of allocated file descriptors.
47 pub allocated: u64,
48 /// Number of free file descriptors.
49 ///
50 /// **Deprecated:** This field has been deprecated since Linux 2.6 and is always 0 in modern kernels.
51 /// It does not contain meaningful data.
52 pub free: u64,
53 /// Maximum number of file descriptors (same as `file_max`).
54 pub maximum: u64,
55 }
56
57 impl SysLimits {
58 /// Reads system-wide file descriptor limits from `/proc/sys/fs/`.
59 ///
60 /// # Errors
61 /// Returns an error if any IO operation failed or if the file format is invalid.
62 ///
63 /// # Examples
64 /// ```no_run
65 /// # #[cfg(any(target_os = "linux", target_os = "android"))]
66 /// # {
67 /// use rlimit::SysLimits;
68 ///
69 /// let limits = SysLimits::read().unwrap();
70 /// println!("System file-max: {:?}", limits.file_max);
71 /// println!("Current usage: {:?}", limits.file_nr);
72 /// println!("Per-process nr_open: {:?}", limits.nr_open);
73 /// # }
74 /// ```
75 pub fn read() -> io::Result<Self> {
76 let file_max = read_u64_from_file("/proc/sys/fs/file-max").ok();
77 let file_nr = read_file_nr("/proc/sys/fs/file-nr").ok();
78 let nr_open = read_u64_from_file("/proc/sys/fs/nr_open").ok();
79
80 Ok(Self {
81 file_max,
82 file_nr,
83 nr_open,
84 })
85 }
86
87 /// Writes the `file_max` value to `/proc/sys/fs/file-max`.
88 ///
89 /// This operation typically requires root privileges or `CAP_SYS_ADMIN` capability.
90 ///
91 /// # Errors
92 /// Returns an error if the write operation failed, which can happen if:
93 /// - The process lacks sufficient privileges
94 /// - The value is invalid
95 /// - The filesystem is read-only
96 ///
97 /// # Examples
98 /// ```no_run
99 /// # #[cfg(any(target_os = "linux", target_os = "android"))]
100 /// # {
101 /// use rlimit::SysLimits;
102 ///
103 /// // This typically requires root privileges
104 /// SysLimits::set_file_max(1048576).unwrap();
105 /// # }
106 /// ```
107 pub fn set_file_max(value: u64) -> io::Result<()> {
108 write_u64_to_file("/proc/sys/fs/file-max", value)
109 }
110
111 /// Writes the `nr_open` value to `/proc/sys/fs/nr_open`.
112 ///
113 /// This operation typically requires root privileges or `CAP_SYS_ADMIN` capability.
114 ///
115 /// # Errors
116 /// Returns an error if the write operation failed, which can happen if:
117 /// - The process lacks sufficient privileges
118 /// - The value is invalid
119 /// - The filesystem is read-only
120 ///
121 /// # Examples
122 /// ```no_run
123 /// # #[cfg(any(target_os = "linux", target_os = "android"))]
124 /// # {
125 /// use rlimit::SysLimits;
126 ///
127 /// // This typically requires root privileges
128 /// SysLimits::set_nr_open(1048576).unwrap();
129 /// # }
130 /// ```
131 pub fn set_nr_open(value: u64) -> io::Result<()> {
132 write_u64_to_file("/proc/sys/fs/nr_open", value)
133 }
134 }
135
136 /// Reads a u64 value from a file in `/proc/sys/fs/`.
137 fn read_u64_from_file(path: impl AsRef<Path>) -> io::Result<u64> {
138 let content = fs::read_to_string(path)?;
139 content
140 .trim()
141 .parse::<u64>()
142 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
143 }
144
145 /// Reads file descriptor statistics from `/proc/sys/fs/file-nr`.
146 ///
147 /// The file contains three whitespace-separated values: allocated, free, and maximum.
148 fn read_file_nr(path: impl AsRef<Path>) -> io::Result<FileNr> {
149 let content = fs::read_to_string(path)?;
150 let parts: Vec<&str> = content.split_whitespace().collect();
151
152 if parts.len() != 3 {
153 return Err(io::Error::new(
154 io::ErrorKind::InvalidData,
155 format!("Expected 3 values in file-nr, got {}", parts.len()),
156 ));
157 }
158
159 let allocated = parts[0]
160 .parse::<u64>()
161 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
162 let free = parts[1]
163 .parse::<u64>()
164 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
165 let maximum = parts[2]
166 .parse::<u64>()
167 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
168
169 Ok(FileNr {
170 allocated,
171 free,
172 maximum,
173 })
174 }
175
176 /// Writes a u64 value to a file in `/proc/sys/fs/`.
177 fn write_u64_to_file(path: impl AsRef<Path>, value: u64) -> io::Result<()> {
178 fs::write(path, value.to_string())
179 }
180
181 #[cfg(test)]
182 mod tests {
183 use super::*;
184
185 #[test]
186 fn test_read_system_limits() {
187 // This test only verifies that the function doesn't crash
188 // The actual values depend on the system configuration
189 let result = SysLimits::read();
190
191 // Should succeed on Linux/Android systems
192 if cfg!(any(target_os = "linux", target_os = "android")) {
193 let limits = result.unwrap();
194
195 // At least one of the fields should be populated
196 assert!(
197 limits.file_max.is_some() || limits.file_nr.is_some() || limits.nr_open.is_some(),
198 "At least one limit should be readable"
199 );
200
201 // If file_nr is present, validate its structure
202 if let Some(file_nr) = limits.file_nr {
203 // Maximum should match file_max if both are present
204 if let Some(file_max) = limits.file_max {
205 assert_eq!(file_nr.maximum, file_max);
206 }
207 }
208 }
209 }
210
211 #[test]
212 fn test_file_nr_parsing() {
213 // Test the internal parsing logic with mock data
214 use std::io::Write;
215
216 let temp_dir = std::env::temp_dir();
217 let test_file = temp_dir.join(format!(
218 "test_file_nr_{:?}.txt",
219 std::thread::current().id()
220 ));
221
222 // Write test data
223 let mut file = fs::File::create(&test_file).unwrap();
224 write!(file, "2208\t0\t9223372036854775807").unwrap();
225 file.flush().unwrap();
226 drop(file);
227
228 // Read and verify
229 let result = read_file_nr(&test_file).unwrap();
230 assert_eq!(result.allocated, 2208);
231 assert_eq!(result.free, 0);
232 assert_eq!(result.maximum, 9_223_372_036_854_775_807);
233
234 // Clean up
235 fs::remove_file(&test_file).ok();
236 }
237
238 #[test]
239 fn test_u64_parsing() {
240 use std::io::Write;
241
242 let temp_dir = std::env::temp_dir();
243 let test_file = temp_dir.join(format!(
244 "test_u64_{:?}.txt",
245 std::thread::current().id()
246 ));
247
248 // Write test data
249 let mut file = fs::File::create(&test_file).unwrap();
250 writeln!(file, "1048576").unwrap();
251 file.flush().unwrap();
252 drop(file);
253
254 // Read and verify
255 let result = read_u64_from_file(&test_file).unwrap();
256 assert_eq!(result, 1_048_576);
257
258 // Clean up
259 fs::remove_file(&test_file).ok();
260 }
261 }