/build/source/nativelink-util/src/fs.rs
Line | Count | Source |
1 | | // Copyright 2024 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (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 | | // See LICENSE file for details |
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 | | use core::pin::Pin; |
16 | | use core::sync::atomic::{AtomicUsize, Ordering}; |
17 | | use core::task::{Context, Poll}; |
18 | | use std::fs::{Metadata, Permissions}; |
19 | | use std::io::{self, IoSlice, Seek}; |
20 | | #[cfg(target_os = "linux")] |
21 | | use std::os::unix::io::AsRawFd; |
22 | | use std::path::{Path, PathBuf}; |
23 | | |
24 | | use nativelink_error::{Code, Error, ResultExt, make_err}; |
25 | | use rlimit::increase_nofile_limit; |
26 | | /// We wrap all `tokio::fs` items in our own wrapper so we can limit the number of outstanding |
27 | | /// open files at any given time. This will greatly reduce the chance we'll hit open file limit |
28 | | /// issues. |
29 | | pub use tokio::fs::DirEntry; |
30 | | use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncWrite, ReadBuf, SeekFrom, Take}; |
31 | | use tokio::sync::{Semaphore, SemaphorePermit}; |
32 | | use tracing::{error, info, trace, warn}; |
33 | | |
34 | | use crate::spawn_blocking; |
35 | | |
36 | | /// Default read buffer size when reading to/from disk. |
37 | | pub const DEFAULT_READ_BUFF_SIZE: usize = 0x4000; |
38 | | |
39 | | #[derive(Debug)] |
40 | | pub struct FileSlot { |
41 | | // We hold the permit because once it is dropped it goes back into the queue. |
42 | | _permit: SemaphorePermit<'static>, |
43 | | inner: tokio::fs::File, |
44 | | } |
45 | | |
46 | | impl FileSlot { |
47 | | /// Advise the kernel to drop page cache for this file's contents. |
48 | | /// Only available on Linux; |
49 | | #[cfg(target_os = "linux")] |
50 | 2 | pub fn advise_dontneed(&self) { |
51 | 2 | let fd = self.inner.as_raw_fd(); |
52 | 2 | let ret = unsafe { libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_DONTNEED) }; |
53 | 2 | if ret != 0 { |
54 | 0 | tracing::debug!( |
55 | | fd, |
56 | | ret, |
57 | | "posix_fadvise(DONTNEED) returned non-zero (best-effort, ignoring)", |
58 | | ); |
59 | 2 | } |
60 | 2 | } |
61 | | |
62 | | #[cfg(not(target_os = "linux"))] |
63 | | pub const fn advise_dontneed(&self) { |
64 | | // No-op: posix_fadvise is not available on Mac or Windows. |
65 | | } |
66 | | } |
67 | | |
68 | | /// Enable [`IP_FREEBIND`](`libc::IP_FREEBIND`) before binding a socket. |
69 | | #[cfg(target_os = "linux")] |
70 | 1 | pub fn set_freebind<F: AsRawFd>(socket: &F) -> Result<(), io::Error> { |
71 | 1 | let enable = 1; |
72 | 1 | let optlen = libc::socklen_t::try_from(size_of::<libc::c_int>()) |
73 | 1 | .expect("size of c_int always fits in socklen_t"); |
74 | | |
75 | | // SAFETY: we pass in a valid fd, initialized optval, and matching optlen. |
76 | 1 | let ret = unsafe { |
77 | 1 | libc::setsockopt( |
78 | 1 | socket.as_raw_fd(), |
79 | | libc::IPPROTO_IP, |
80 | | libc::IP_FREEBIND, |
81 | 1 | core::ptr::addr_of!(enable).cast(), |
82 | 1 | optlen, |
83 | | ) |
84 | | }; |
85 | 1 | if ret == 0 { |
86 | 1 | Ok(()) |
87 | | } else { |
88 | 0 | Err(io::Error::last_os_error()) |
89 | | } |
90 | 1 | } |
91 | | |
92 | | #[cfg(not(target_os = "linux"))] |
93 | | pub const fn set_freebind<F>(_socket: &F) -> Result<(), io::Error> { |
94 | | Ok(()) |
95 | | } |
96 | | |
97 | | impl AsRef<tokio::fs::File> for FileSlot { |
98 | 1.72k | fn as_ref(&self) -> &tokio::fs::File { |
99 | 1.72k | &self.inner |
100 | 1.72k | } |
101 | | } |
102 | | |
103 | | impl AsMut<tokio::fs::File> for FileSlot { |
104 | 2 | fn as_mut(&mut self) -> &mut tokio::fs::File { |
105 | 2 | &mut self.inner |
106 | 2 | } |
107 | | } |
108 | | |
109 | | impl AsyncRead for FileSlot { |
110 | 5.27k | fn poll_read( |
111 | 5.27k | mut self: Pin<&mut Self>, |
112 | 5.27k | cx: &mut Context<'_>, |
113 | 5.27k | buf: &mut ReadBuf<'_>, |
114 | 5.27k | ) -> Poll<Result<(), tokio::io::Error>> { |
115 | 5.27k | Pin::new(&mut self.inner).poll_read(cx, buf) |
116 | 5.27k | } |
117 | | } |
118 | | |
119 | | impl AsyncSeek for FileSlot { |
120 | 44 | fn start_seek(mut self: Pin<&mut Self>, position: SeekFrom) -> Result<(), tokio::io::Error> { |
121 | 44 | Pin::new(&mut self.inner).start_seek(position) |
122 | 44 | } |
123 | | |
124 | 132 | fn poll_complete( |
125 | 132 | mut self: Pin<&mut Self>, |
126 | 132 | cx: &mut Context<'_>, |
127 | 132 | ) -> Poll<Result<u64, tokio::io::Error>> { |
128 | 132 | Pin::new(&mut self.inner).poll_complete(cx) |
129 | 132 | } |
130 | | } |
131 | | |
132 | | impl AsyncWrite for FileSlot { |
133 | 249 | fn poll_write( |
134 | 249 | mut self: Pin<&mut Self>, |
135 | 249 | cx: &mut Context<'_>, |
136 | 249 | buf: &[u8], |
137 | 249 | ) -> Poll<Result<usize, tokio::io::Error>> { |
138 | 249 | Pin::new(&mut self.inner).poll_write(cx, buf) |
139 | 249 | } |
140 | | |
141 | 3.30k | fn poll_flush( |
142 | 3.30k | mut self: Pin<&mut Self>, |
143 | 3.30k | cx: &mut Context<'_>, |
144 | 3.30k | ) -> Poll<Result<(), tokio::io::Error>> { |
145 | 3.30k | Pin::new(&mut self.inner).poll_flush(cx) |
146 | 3.30k | } |
147 | | |
148 | 0 | fn poll_shutdown( |
149 | 0 | mut self: Pin<&mut Self>, |
150 | 0 | cx: &mut Context<'_>, |
151 | 0 | ) -> Poll<Result<(), tokio::io::Error>> { |
152 | 0 | Pin::new(&mut self.inner).poll_shutdown(cx) |
153 | 0 | } |
154 | | |
155 | 1.47k | fn poll_write_vectored( |
156 | 1.47k | mut self: Pin<&mut Self>, |
157 | 1.47k | cx: &mut Context<'_>, |
158 | 1.47k | bufs: &[IoSlice<'_>], |
159 | 1.47k | ) -> Poll<Result<usize, tokio::io::Error>> { |
160 | 1.47k | Pin::new(&mut self.inner).poll_write_vectored(cx, bufs) |
161 | 1.47k | } |
162 | | |
163 | 1.47k | fn is_write_vectored(&self) -> bool { |
164 | 1.47k | self.inner.is_write_vectored() |
165 | 1.47k | } |
166 | | } |
167 | | |
168 | | // Note: If the default changes make sure you update the documentation in |
169 | | // `config/cas_server.rs`. |
170 | | pub const DEFAULT_OPEN_FILE_LIMIT: usize = 24 * 1024; // 24k. |
171 | | static OPEN_FILE_LIMIT: AtomicUsize = AtomicUsize::new(DEFAULT_OPEN_FILE_LIMIT); |
172 | | pub static OPEN_FILE_SEMAPHORE: Semaphore = Semaphore::const_new(DEFAULT_OPEN_FILE_LIMIT); |
173 | | |
174 | | /// Try to acquire a permit from the open file semaphore. |
175 | | #[inline] |
176 | 30.5k | pub async fn get_permit() -> Result<SemaphorePermit<'static>, Error> { |
177 | 30.5k | trace!( |
178 | 30.4k | available_permits = OPEN_FILE_SEMAPHORE.available_permits(), |
179 | | "getting FS permit" |
180 | | ); |
181 | 30.5k | OPEN_FILE_SEMAPHORE |
182 | 30.5k | .acquire() |
183 | 30.5k | .await |
184 | 30.5k | .map_err(|e| make_err!0 (Code::Internal0 , "Open file semaphore closed {:?}", e)) |
185 | 30.5k | } |
186 | | /// Acquire a permit from the open file semaphore and call a raw function. |
187 | | #[inline] |
188 | 5.90k | pub async fn call_with_permit<F, T>(f: F) -> Result<T, Error> |
189 | 5.90k | where |
190 | 5.90k | F: FnOnce(SemaphorePermit<'static>) -> Result<T, Error> + Send + 'static, |
191 | 5.90k | T: Send + 'static, |
192 | 5.90k | { |
193 | 5.90k | let permit = get_permit().await?0 ; |
194 | 5.90k | spawn_blocking!("fs_call_with_permit", move || f5.90k (permit5.90k )) |
195 | 5.90k | .await |
196 | 5.89k | .unwrap_or_else(|e| {0 |
197 | 0 | Err(Error::from_std_err(Code::Internal, &e).append("background task failed")) |
198 | 0 | }) |
199 | 5.89k | } |
200 | | |
201 | | /// Sets the soft nofile limit to `desired_open_file_limit` and adjusts |
202 | | /// `OPEN_FILE_SEMAPHORE` accordingly. |
203 | | /// |
204 | | /// # Panics |
205 | | /// |
206 | | /// If any type conversion fails. This can't happen if `usize` is smaller than |
207 | | /// `u64`. |
208 | 0 | pub fn set_open_file_limit(desired_open_file_limit: usize) { |
209 | | // Tokio semaphores have a max of 2^61 - 1 permits. On some platforms |
210 | | // (e.g. macOS) the kernel reports an "unlimited" file limit that exceeds |
211 | | // this, causing a panic when we try to add permits. Cap at a generous but |
212 | | // safe value. |
213 | | const MAX_SAFE_LIMIT: usize = 1 << 30; // ~1 billion |
214 | | |
215 | 0 | let new_open_file_limit = { |
216 | 0 | match increase_nofile_limit( |
217 | 0 | u64::try_from(desired_open_file_limit) |
218 | 0 | .expect("desired_open_file_limit is too large to convert to u64."), |
219 | 0 | ) { |
220 | 0 | Ok(open_file_limit) => { |
221 | 0 | info!("set_open_file_limit() assigns new open file limit {open_file_limit}.",); |
222 | 0 | usize::try_from(open_file_limit) |
223 | 0 | .expect("open_file_limit is too large to convert to usize.") |
224 | 0 | .min(MAX_SAFE_LIMIT) |
225 | | } |
226 | 0 | Err(e) => { |
227 | 0 | error!( |
228 | | "set_open_file_limit() failed to assign open file limit. Maybe system does not have ulimits, continuing anyway. - {e:?}", |
229 | | ); |
230 | 0 | DEFAULT_OPEN_FILE_LIMIT |
231 | | } |
232 | | } |
233 | | }; |
234 | | // TODO(jaroeichler): Can we give a better estimate? |
235 | 0 | if new_open_file_limit < DEFAULT_OPEN_FILE_LIMIT { |
236 | 0 | warn!( |
237 | | "The new open file limit ({new_open_file_limit}) is below the recommended value of {DEFAULT_OPEN_FILE_LIMIT}. Consider raising max_open_files.", |
238 | | ); |
239 | 0 | } |
240 | | |
241 | | // Use only 80% of the open file limit for permits from OPEN_FILE_SEMAPHORE |
242 | | // to give extra room for other file descriptors like sockets, pipes, and |
243 | | // other things. |
244 | 0 | let reduced_open_file_limit = new_open_file_limit.saturating_sub(new_open_file_limit / 5); |
245 | 0 | let previous_open_file_limit = OPEN_FILE_LIMIT.load(Ordering::Acquire); |
246 | | // No permit should be acquired yet, so this warning should not occur. |
247 | 0 | if (OPEN_FILE_SEMAPHORE.available_permits() + reduced_open_file_limit) |
248 | 0 | < previous_open_file_limit |
249 | | { |
250 | 0 | warn!( |
251 | | "There are not enough available permits to remove {previous_open_file_limit} - {reduced_open_file_limit} permits.", |
252 | | ); |
253 | 0 | } |
254 | 0 | if previous_open_file_limit <= reduced_open_file_limit { |
255 | 0 | OPEN_FILE_LIMIT.fetch_add( |
256 | 0 | reduced_open_file_limit - previous_open_file_limit, |
257 | 0 | Ordering::Release, |
258 | 0 | ); |
259 | 0 | OPEN_FILE_SEMAPHORE.add_permits(reduced_open_file_limit - previous_open_file_limit); |
260 | 0 | } else { |
261 | 0 | OPEN_FILE_LIMIT.fetch_sub( |
262 | 0 | previous_open_file_limit - reduced_open_file_limit, |
263 | 0 | Ordering::Release, |
264 | 0 | ); |
265 | 0 | OPEN_FILE_SEMAPHORE.forget_permits(previous_open_file_limit - reduced_open_file_limit); |
266 | 0 | } |
267 | 0 | } |
268 | | |
269 | 94 | pub fn get_open_files_for_test() -> usize { |
270 | 94 | OPEN_FILE_LIMIT.load(Ordering::Acquire) - OPEN_FILE_SEMAPHORE.available_permits() |
271 | 94 | } |
272 | | |
273 | 616 | pub async fn open_file( |
274 | 616 | path: impl AsRef<Path>, |
275 | 616 | start: u64, |
276 | 616 | limit: u64, |
277 | 616 | ) -> Result<Take<FileSlot>, Error> { |
278 | 616 | let path = path.as_ref().to_owned(); |
279 | 616 | let (permit613 , os_file613 ) = call_with_permit(move |permit| { |
280 | 613 | let mut os_file = |
281 | 616 | std::fs::File::open(&path).err_tip(|| format!3 ("Could not open {}", path.display()3 ))?3 ; |
282 | 613 | if start > 0 { |
283 | 0 | os_file |
284 | 0 | .seek(SeekFrom::Start(start)) |
285 | 0 | .err_tip(|| format!("Could not seek to {start} in {}", path.display()))?; |
286 | 613 | } |
287 | 613 | Ok((permit, os_file)) |
288 | 616 | }) |
289 | 616 | .await?3 ; |
290 | 613 | Ok(FileSlot { |
291 | 613 | _permit: permit, |
292 | 613 | inner: tokio::fs::File::from_std(os_file), |
293 | 613 | } |
294 | 613 | .take(limit)) |
295 | 616 | } |
296 | | |
297 | 1.72k | pub async fn create_file(path: impl AsRef<Path>) -> Result<FileSlot, Error> { |
298 | 1.72k | let path = path.as_ref().to_owned(); |
299 | 1.72k | let (permit, os_file) = call_with_permit(move |permit| { |
300 | | Ok(( |
301 | 1.72k | permit, |
302 | 1.72k | std::fs::File::options() |
303 | 1.72k | .read(true) |
304 | 1.72k | .write(true) |
305 | 1.72k | .create(true) |
306 | 1.72k | .truncate(true) |
307 | 1.72k | .open(&path) |
308 | 1.72k | .err_tip(|| format!0 ("Could not open {}", path.display()0 ))?0 , |
309 | | )) |
310 | 1.72k | }) |
311 | 1.72k | .await?0 ; |
312 | 1.72k | Ok(FileSlot { |
313 | 1.72k | _permit: permit, |
314 | 1.72k | inner: tokio::fs::File::from_std(os_file), |
315 | 1.72k | }) |
316 | 1.72k | } |
317 | | |
318 | 1 | pub async fn hard_link(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<(), Error> { |
319 | 1 | let src = src.as_ref().to_owned(); |
320 | 1 | let dst = dst.as_ref().to_owned(); |
321 | 1 | call_with_permit(move |_| std::fs::hard_link(src, dst).map_err(Into::<Error>::into)).await |
322 | 1 | } |
323 | | |
324 | | /// Hardlinks many files under a single permit and a single `spawn_blocking` |
325 | | /// dispatch, returning one result per input in the same order. |
326 | | /// |
327 | | /// [`hard_link`] pays a semaphore acquire plus a `spawn_blocking` hop per call, |
328 | | /// and both dwarf the `hard_link(2)` syscall itself, which is a few microseconds |
329 | | /// on tmpfs. Staging an input tree of thousands of small files therefore spends |
330 | | /// most of its wall time in the tokio scheduler rather than in the kernel. |
331 | | /// Batching amortizes the acquire and the dispatch over the whole batch. |
332 | | /// |
333 | | /// A single permit covers the batch because `hard_link(2)` is a metadata |
334 | | /// operation that never leaves a file descriptor open, so it does not consume |
335 | | /// the open-file budget [`OPEN_FILE_SEMAPHORE`] exists to protect. |
336 | | /// |
337 | | /// This does change the backpressure profile; the permit no longer paces |
338 | | /// individual syscalls, only whole batches, and one blocking thread is held for |
339 | | /// the length of a batch rather than for one syscall. On Linux and tmpfs, where |
340 | | /// this was measured, that trades well because the per-call dispatch was the |
341 | | /// cost. A filesystem that serializes metadata operations internally, as APFS |
342 | | /// does on a per-volume lock, gets a different bargain: less parallel |
343 | | /// contention, but a long batch occupies its thread throughout. Size batches |
344 | | /// accordingly. |
345 | 0 | pub async fn hard_link_many( |
346 | 0 | links: Vec<(PathBuf, PathBuf)>, |
347 | 30 | ) -> Result<Vec<Result<(), Error>>, Error> { |
348 | 30 | call_with_permit(move |_| { |
349 | 30 | Ok(links |
350 | 30 | .into_iter() |
351 | 30 | .map(|(src, dst)| std::fs::hard_link15 (src15 , dst15 ).map_err15 (Into::<Error>::into)) |
352 | 30 | .collect()) |
353 | 30 | }) |
354 | 30 | .await |
355 | 30 | } |
356 | | |
357 | 1.73k | pub async fn set_permissions(src: impl AsRef<Path>, perm: Permissions) -> Result<(), Error> { |
358 | 1.73k | let src = src.as_ref().to_owned(); |
359 | 1.73k | call_with_permit(move |_| std::fs::set_permissions(src, perm).map_err(Into::<Error>::into)) |
360 | 1.73k | .await |
361 | 1.73k | } |
362 | | |
363 | | /// Creates many directories under a single permit and a single `spawn_blocking` |
364 | | /// dispatch, each parent before its children. |
365 | | /// |
366 | | /// An existing directory is an error, exactly as [`create_dir`] reports it. |
367 | | /// |
368 | | /// See [`hard_link_many`] for why batching matters here: the `mkdir(2)` syscall |
369 | | /// is dwarfed by the semaphore acquire and `spawn_blocking` hop, and an input |
370 | | /// tree contributes hundreds of directories. |
371 | 31 | pub async fn create_dir_many(mut dirs: Vec<PathBuf>) -> Result<(), Error>0 {
|
372 | | // Sorting puts every parent ahead of its children, since a parent's path is |
373 | | // a prefix of theirs. We do this instead of using `create_dir_all` below |
374 | | // because we want to fail on existing directories: on case-insensitive |
375 | | // filesystems, that will ensure that we don't silently merge two trees in |
376 | | // the event of a different-in-case-only collision. |
377 | 31 | dirs.sort_unstable(); |
378 | 31 | call_with_permit(move |_| { |
379 | 31 | for dir16 in dirs { |
380 | 16 | std::fs::create_dir(&dir).map_err(|e| {2 |
381 | 2 | Error::from(e).append(format!("Could not create directory {}", dir.display())) |
382 | 2 | })?; |
383 | | } |
384 | 29 | Ok(()) |
385 | 31 | }) |
386 | 31 | .await |
387 | 31 | } |
388 | | |
389 | 255 | pub async fn create_dir(path: impl AsRef<Path>) -> Result<(), Error> { |
390 | 255 | let path = path.as_ref().to_owned(); |
391 | 255 | call_with_permit(move |_| std::fs::create_dir(path).map_err(Into::<Error>::into)).await |
392 | 255 | } |
393 | | |
394 | 504 | pub async fn create_dir_all(path: impl AsRef<Path>) -> Result<(), Error> { |
395 | 504 | let path = path.as_ref().to_owned(); |
396 | 504 | call_with_permit(move |_| std::fs::create_dir_all(path).map_err(Into::<Error>::into)).await |
397 | 504 | } |
398 | | |
399 | | #[cfg(target_family = "unix")] |
400 | 3 | pub async fn symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<(), Error> { |
401 | | // TODO: add a test for #2051: deadlock with large number of files |
402 | 3 | let _permit = get_permit().await?0 ; |
403 | 3 | tokio::fs::symlink(src, dst).await.map_err(Into::into) |
404 | 3 | } |
405 | | |
406 | 6 | pub async fn read_link(path: impl AsRef<Path>) -> Result<PathBuf, Error> { |
407 | 6 | let path = path.as_ref().to_owned(); |
408 | 6 | call_with_permit(move |_| std::fs::read_link(path).map_err(Into::<Error>::into)).await |
409 | 6 | } |
410 | | |
411 | | #[derive(Debug)] |
412 | | pub struct ReadDir { |
413 | | // We hold the permit because once it is dropped it goes back into the queue. |
414 | | permit: SemaphorePermit<'static>, |
415 | | inner: tokio::fs::ReadDir, |
416 | | } |
417 | | |
418 | | impl ReadDir { |
419 | 583 | pub fn into_inner(self) -> (SemaphorePermit<'static>, tokio::fs::ReadDir) { |
420 | 583 | (self.permit, self.inner) |
421 | 583 | } |
422 | | } |
423 | | |
424 | | impl AsRef<tokio::fs::ReadDir> for ReadDir { |
425 | 0 | fn as_ref(&self) -> &tokio::fs::ReadDir { |
426 | 0 | &self.inner |
427 | 0 | } |
428 | | } |
429 | | |
430 | | impl AsMut<tokio::fs::ReadDir> for ReadDir { |
431 | 0 | fn as_mut(&mut self) -> &mut tokio::fs::ReadDir { |
432 | 0 | &mut self.inner |
433 | 0 | } |
434 | | } |
435 | | |
436 | 585 | pub async fn read_dir(path: impl AsRef<Path>) -> Result<ReadDir, Error> { |
437 | 585 | let path = path.as_ref().to_owned(); |
438 | 585 | let (permit, inner) = call_with_permit(move |permit| { |
439 | | Ok(( |
440 | 585 | permit, |
441 | 585 | tokio::runtime::Handle::current() |
442 | 585 | .block_on(tokio::fs::read_dir(path)) |
443 | 585 | .map_err(Into::<Error>::into)?0 , |
444 | | )) |
445 | 585 | }) |
446 | 585 | .await?0 ; |
447 | 585 | Ok(ReadDir { permit, inner }) |
448 | 585 | } |
449 | | |
450 | 18 | pub async fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<(), Error> { |
451 | 18 | let from = from.as_ref().to_owned(); |
452 | 18 | let to = to.as_ref().to_owned(); |
453 | 18 | call_with_permit(move |_| std::fs::rename(from, to).map_err(Into::<Error>::into)).await |
454 | 18 | } |
455 | | |
456 | 41 | pub async fn remove_file(path: impl AsRef<Path>) -> Result<(), Error> { |
457 | 41 | let path = path.as_ref().to_owned(); |
458 | 41 | call_with_permit(move |_| std::fs::remove_file40 (path40 ).map_err40 (Into::<Error>::into)).await |
459 | 36 | } |
460 | | |
461 | | /// Removes an empty directory. Errors if the directory is not empty; use |
462 | | /// [`remove_dir_all`] when the contents should be removed too. |
463 | 2 | pub async fn remove_dir(path: impl AsRef<Path>) -> Result<(), Error> { |
464 | 2 | let path = path.as_ref().to_owned(); |
465 | 2 | call_with_permit(move |_| std::fs::remove_dir(path).map_err(Into::<Error>::into)).await |
466 | 2 | } |
467 | | |
468 | 2 | pub async fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf, Error> { |
469 | 2 | let path = path.as_ref().to_owned(); |
470 | 2 | call_with_permit(move |_| std::fs::canonicalize(path).map_err(Into::<Error>::into)).await |
471 | 2 | } |
472 | | |
473 | 55 | pub async fn metadata(path: impl AsRef<Path>) -> Result<Metadata, Error> { |
474 | 55 | let path = path.as_ref().to_owned(); |
475 | 55 | call_with_permit(move |_| std::fs::metadata(path).map_err(Into::<Error>::into)).await |
476 | 55 | } |
477 | | |
478 | | /// Tests many paths for existence under a single permit and a single |
479 | | /// `spawn_blocking` dispatch, returning one answer per input in the same order. |
480 | | /// |
481 | | /// A `stat(2)` on a warm tmpfs costs far less than the permit acquisition and |
482 | | /// thread hop needed to dispatch it, so callers checking a whole input tree pay |
483 | | /// almost entirely dispatch overhead when they ask one path at a time. |
484 | | /// |
485 | | /// Any error is reported as `false`, since every failure mode (absent, |
486 | | /// dangling, unreadable parent) answers "can I use this path" the same way. |
487 | 30 | pub async fn exists_many(paths: Vec<PathBuf>) -> Result<Vec<bool>, Error>0 {
|
488 | 30 | call_with_permit(move |_| { |
489 | 30 | Ok(paths |
490 | 30 | .into_iter() |
491 | 30 | .map(|path| std::fs::metadata(path)6 .is_ok6 ()) |
492 | 30 | .collect()) |
493 | 30 | }) |
494 | 30 | .await |
495 | 30 | } |
496 | | |
497 | 13 | pub async fn read(path: impl AsRef<Path>) -> Result<Vec<u8>, Error> { |
498 | 13 | let path = path.as_ref().to_owned(); |
499 | 13 | call_with_permit(move |_| std::fs::read(path).map_err(Into::<Error>::into)).await |
500 | 13 | } |
501 | | |
502 | 16 | pub async fn symlink_metadata(path: impl AsRef<Path>) -> Result<Metadata, Error> { |
503 | 16 | let path = path.as_ref().to_owned(); |
504 | 16 | call_with_permit(move |_| std::fs::symlink_metadata(path).map_err(Into::<Error>::into)).await |
505 | 16 | } |
506 | | |
507 | | // We can't just use the stock remove_dir_all as it falls over if someone's set readonly |
508 | | // permissions. This version walks the directories and fixes the permissions where needed |
509 | | // before deleting everything. |
510 | | #[cfg(not(target_family = "windows"))] |
511 | 238 | fn internal_remove_dir_all(path: impl AsRef<Path>) -> Result<(), Error> { |
512 | | // Because otherwise Windows builds complain about these things not being used |
513 | | use std::io::ErrorKind; |
514 | | use std::os::unix::fs::PermissionsExt; |
515 | | |
516 | | use tracing::debug; |
517 | | use walkdir::WalkDir; |
518 | | |
519 | 239 | for entry in WalkDir::new238 (&path238 ) { |
520 | 239 | let Ok(entry236 ) = &entry else { |
521 | 3 | debug!(?entry, "Can't get entry, assuming already deleted"); |
522 | 3 | continue; |
523 | | }; |
524 | 236 | let metadata = entry.metadata()?0 ; |
525 | 236 | if metadata.is_dir() { |
526 | 236 | match std::fs::remove_dir_all(entry.path()) { |
527 | 235 | Ok(()) => {} |
528 | 1 | Err(e) if e.kind() == ErrorKind::PermissionDenied => { |
529 | 1 | std::fs::set_permissions(entry.path(), Permissions::from_mode(0o700)).err_tip( |
530 | 0 | || format!("Setting permissions for {}", entry.path().display()), |
531 | 0 | )?; |
532 | | } |
533 | 0 | e @ Err(_) => e.err_tip(|| format!("Removing {}", entry.path().display()))?, |
534 | | } |
535 | 0 | } else if metadata.is_file() { |
536 | 0 | std::fs::set_permissions(entry.path(), Permissions::from_mode(0o600)) |
537 | 0 | .err_tip(|| format!("Setting permissions for {}", entry.path().display()))?; |
538 | 0 | } |
539 | | } |
540 | | |
541 | | // should now be safe to delete after we fixed all the permissions in the walk loop |
542 | 238 | match std::fs::remove_dir_all(&path) { |
543 | 1 | Ok(()) => {} |
544 | 237 | Err(e) if e.kind() == ErrorKind::NotFound => {} |
545 | 0 | e @ Err(_) => e.err_tip(|| { |
546 | 0 | format!( |
547 | | "Removing {} after permissions fixes", |
548 | 0 | path.as_ref().display() |
549 | | ) |
550 | 0 | })?, |
551 | | } |
552 | 238 | Ok(()) |
553 | 238 | } |
554 | | |
555 | | // We can't set the permissions easily in Windows, so just fallback to |
556 | | // the stock Rust remove_dir_all |
557 | | #[cfg(target_family = "windows")] |
558 | | fn internal_remove_dir_all(path: impl AsRef<Path>) -> Result<(), Error> { |
559 | | std::fs::remove_dir_all(&path)?; |
560 | | Ok(()) |
561 | | } |
562 | | |
563 | 238 | pub async fn remove_dir_all(path: impl AsRef<Path>) -> Result<(), Error> { |
564 | 238 | let path = path.as_ref().to_owned(); |
565 | 238 | call_with_permit(move |_| internal_remove_dir_all(path)).await |
566 | 238 | } |