blob: e8df4244151c641220617a29c85c5decfcc18da9 [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
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
Jiyong Parkbb4a9872021-09-06 15:59:21 +090017use anyhow::{anyhow, bail, Result};
Jiyong Park86c9b082021-06-04 19:03:48 +090018use nix::sys::stat::FileStat;
Jiyong Park86c9b082021-06-04 19:03:48 +090019use std::fs::File;
20use std::os::unix::fs::FileTypeExt;
21use std::os::unix::io::AsRawFd;
22use std::path::Path;
23use std::thread;
24use std::time::{Duration, Instant};
25
26/// Returns when the file exists on the given `path` or timeout (1s) occurs.
27pub 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
Shikha Panwar27cb7e72022-10-13 20:34:45 +000040/// Wait for the path to disappear
41#[cfg(test)]
42pub 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
Jiyong Park86c9b082021-06-04 19:03:48 +090055/// Returns hexadecimal reprentation of a given byte array.
56pub fn hexstring_from(s: &[u8]) -> String {
Jiyong Park99a35b82021-06-07 10:13:44 +090057 s.iter().map(|byte| format!("{:02x}", byte)).reduce(|i, j| i + &j).unwrap_or_default()
Jiyong Park86c9b082021-06-04 19:03:48 +090058}
59
Jiyong Parkbb4a9872021-09-06 15:59:21 +090060/// Parses a hexadecimal string into a byte array
61pub fn parse_hexstring(s: &str) -> Result<Vec<u8>> {
62 let len = s.len();
63 if len % 2 != 0 {
64 bail!("length {} is not even", len)
65 } else {
66 (0..len)
67 .step_by(2)
68 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| anyhow!(e)))
69 .collect()
70 }
71}
72
Jiyong Park86c9b082021-06-04 19:03:48 +090073/// fstat that accepts a path rather than FD
74pub fn fstat(p: &Path) -> Result<FileStat> {
75 let f = File::open(p)?;
76 Ok(nix::sys::stat::fstat(f.as_raw_fd())?)
77}
78
79// From include/uapi/linux/fs.h
80const BLK: u8 = 0x12;
81const BLKGETSIZE64: u8 = 114;
82nix::ioctl_read!(_blkgetsize64, BLK, BLKGETSIZE64, libc::size_t);
83
84/// Gets the size of a block device
85pub fn blkgetsize64(p: &Path) -> Result<u64> {
86 let f = File::open(p)?;
87 if !f.metadata()?.file_type().is_block_device() {
88 bail!("{:?} is not a block device", p);
89 }
90 let mut size: usize = 0;
91 // SAFETY: kernel copies the return value out to `size`. The file is kept open until the end of
92 // this function.
93 unsafe { _blkgetsize64(f.as_raw_fd(), &mut size) }?;
94 Ok(size as u64)
95}