1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 use anyhow::{bail, Result};
18 use nix::sys::stat::FileStat;
19 use std::fs::File;
20 use std::os::unix::fs::FileTypeExt;
21 use std::os::unix::io::AsRawFd;
22 use std::path::Path;
23 use std::thread;
24 use std::time::{Duration, Instant};
25 
26 /// Returns when the file exists on the given `path` or timeout (1s) occurs.
wait_for_path<P: AsRef<Path>>(path: P) -> Result<()>27 pub fn wait_for_path<P: AsRef<Path>>(path: P) -> Result<()> {
28     const TIMEOUT: Duration = Duration::from_secs(1);
29     const INTERVAL: Duration = Duration::from_millis(10);
30     let begin = Instant::now();
31     while !path.as_ref().exists() {
32         if begin.elapsed() > TIMEOUT {
33             bail!("{:?} not found. TIMEOUT.", path.as_ref());
34         }
35         thread::sleep(INTERVAL);
36     }
37     Ok(())
38 }
39 
40 /// Wait for the path to disappear
41 #[cfg(test)]
wait_for_path_disappears<P: AsRef<Path>>(path: P) -> Result<()>42 pub fn wait_for_path_disappears<P: AsRef<Path>>(path: P) -> Result<()> {
43     const TIMEOUT: Duration = Duration::from_secs(1);
44     const INTERVAL: Duration = Duration::from_millis(10);
45     let begin = Instant::now();
46     while !path.as_ref().exists() {
47         if begin.elapsed() > TIMEOUT {
48             bail!("{:?} not disappearing. TIMEOUT.", path.as_ref());
49         }
50         thread::sleep(INTERVAL);
51     }
52     Ok(())
53 }
54 
55 /// fstat that accepts a path rather than FD
fstat(p: &Path) -> Result<FileStat>56 pub fn fstat(p: &Path) -> Result<FileStat> {
57     let f = File::open(p)?;
58     Ok(nix::sys::stat::fstat(f.as_raw_fd())?)
59 }
60 
61 // From include/uapi/linux/fs.h
62 const BLK: u8 = 0x12;
63 const BLKGETSIZE64: u8 = 114;
64 nix::ioctl_read!(_blkgetsize64, BLK, BLKGETSIZE64, libc::size_t);
65 
66 /// Gets the size of a block device
blkgetsize64(p: &Path) -> Result<u64>67 pub fn blkgetsize64(p: &Path) -> Result<u64> {
68     let f = File::open(p)?;
69     if !f.metadata()?.file_type().is_block_device() {
70         bail!("{:?} is not a block device", p);
71     }
72     let mut size: usize = 0;
73     // SAFETY: kernel copies the return value out to `size`. The file is kept open until the end of
74     // this function.
75     unsafe { _blkgetsize64(f.as_raw_fd(), &mut size) }?;
76     Ok(size as u64)
77 }
78