formatting fixup

make fmt
(cargo fmt --all)

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2019-08-05 14:14:09 +02:00
parent 863a16a5bc
commit ccce46eba4
2 changed files with 78 additions and 64 deletions

View File

@ -13,7 +13,9 @@ use proxmox_tools::fs::file_read_firstline;
/// POSIX sysconf call /// POSIX sysconf call
pub fn sysconf(name: i32) -> i64 { pub fn sysconf(name: i32) -> i64 {
extern { fn sysconf(name: i32) -> i64; } extern "C" {
fn sysconf(name: i32) -> i64;
}
unsafe { sysconf(name) } unsafe { sysconf(name) }
} }
@ -44,7 +46,10 @@ pub fn read_proc_pid_stat(pid: libc::pid_t) -> Result<ProcFsPidStat, Error> {
if let Some(cap) = REGEX.captures(&statstr) { if let Some(cap) = REGEX.captures(&statstr) {
if pid != cap["pid"].parse::<i32>().unwrap() { if pid != cap["pid"].parse::<i32>().unwrap() {
bail!("unable to read pid stat for process '{}' - got wrong pid", pid); bail!(
"unable to read pid stat for process '{}' - got wrong pid",
pid
);
} }
return Ok(ProcFsPidStat { return Ok(ProcFsPidStat {
@ -168,7 +173,9 @@ pub struct ProcFsCPUInfo {
static CPU_INFO: Option<ProcFsCPUInfo> = None; static CPU_INFO: Option<ProcFsCPUInfo> = None;
pub fn read_cpuinfo() -> Result<ProcFsCPUInfo, Error> { pub fn read_cpuinfo() -> Result<ProcFsCPUInfo, Error> {
if let Some(cpu_info) = &CPU_INFO { return Ok(cpu_info.clone()); } if let Some(cpu_info) = &CPU_INFO {
return Ok(cpu_info.clone());
}
let path = "/proc/cpuinfo"; let path = "/proc/cpuinfo";
let file = OpenOptions::new().read(true).open(&path)?; let file = OpenOptions::new().read(true).open(&path)?;
@ -185,11 +192,12 @@ pub fn read_cpuinfo() -> Result<ProcFsCPUInfo, Error> {
let mut socket_ids = HashSet::new(); let mut socket_ids = HashSet::new();
for line in BufReader::new(&file).lines() { for line in BufReader::new(&file).lines() {
let content = line?; let content = line?;
if content.is_empty() { continue; } if content.is_empty() {
continue;
}
let mut content_iter = content.split(":"); let mut content_iter = content.split(":");
match (content_iter.next(), content_iter.next()) { match (content_iter.next(), content_iter.next()) {
(Some(key), Some(value)) => { (Some(key), Some(value)) => match key.trim_end() {
match key.trim_end() {
"processor" => cpuinfo.cpus += 1, "processor" => cpuinfo.cpus += 1,
"model name" => cpuinfo.model = value.trim().to_string(), "model name" => cpuinfo.model = value.trim().to_string(),
"cpu MHz" => cpuinfo.mhz = value.trim().parse::<f64>()?, "cpu MHz" => cpuinfo.mhz = value.trim().parse::<f64>()?,
@ -197,9 +205,8 @@ pub fn read_cpuinfo() -> Result<ProcFsCPUInfo, Error> {
"physical id" => { "physical id" => {
let id = value.trim().parse::<u8>()?; let id = value.trim().parse::<u8>()?;
socket_ids.insert(id); socket_ids.insert(id);
},
_ => continue,
} }
_ => continue,
}, },
_ => bail!("Error while parsing '{}'", path), _ => bail!("Error while parsing '{}'", path),
} }
@ -223,8 +230,7 @@ pub fn read_memory_usage() -> Result<ProcFsMemUsage, Error> {
let ps = 4096; let ps = 4096;
match (values.next(), values.next(), values.next()) { match (values.next(), values.next(), values.next()) {
(Some(Ok(size)), Some(Ok(resident)), Some(Ok(shared))) => (Some(Ok(size)), Some(Ok(resident)), Some(Ok(shared))) => Ok(ProcFsMemUsage {
Ok(ProcFsMemUsage {
size: size * ps, size: size * ps,
resident: resident * ps, resident: resident * ps,
shared: shared * ps, shared: shared * ps,
@ -255,7 +261,7 @@ pub fn read_proc_net_dev() -> Result<Vec<ProcFsNetDev>, Error> {
receive: receive.parse::<u64>()?, receive: receive.parse::<u64>()?,
send: send.parse::<u64>()?, send: send.parse::<u64>()?,
}); });
}, }
_ => bail!("Error while parsing '{}'", path), _ => bail!("Error while parsing '{}'", path),
} }
} }
@ -303,14 +309,20 @@ pub fn read_proc_net_route() -> Result<Vec<ProcFsNetRoute>, Error> {
let mut result = Vec::new(); let mut result = Vec::new();
for line in BufReader::new(&file).lines().skip(1) { for line in BufReader::new(&file).lines().skip(1) {
let content = line?; let content = line?;
if content.is_empty() { continue; } if content.is_empty() {
continue;
}
let mut iter = content.split_whitespace(); let mut iter = content.split_whitespace();
let mut next = || iter.next() let mut next = || {
.ok_or(format_err!("Error while parsing '{}'", path)); iter.next()
.ok_or(format_err!("Error while parsing '{}'", path))
};
let (iface, dest, gateway) = (next()?, next()?, next()?); let (iface, dest, gateway) = (next()?, next()?, next()?);
for _ in 0..3 { next()?; } for _ in 0..3 {
next()?;
}
let (metric, mask, mtu) = (next()?, next()?, next()?); let (metric, mask, mtu) = (next()?, next()?, next()?);
result.push(ProcFsNetRoute { result.push(ProcFsNetRoute {
@ -379,16 +391,24 @@ pub fn read_proc_net_ipv6_route() -> Result<Vec<ProcFsNetIPv6Route>, Error> {
let mut result = Vec::new(); let mut result = Vec::new();
for line in BufReader::new(&file).lines() { for line in BufReader::new(&file).lines() {
let content = line?; let content = line?;
if content.is_empty() { continue; } if content.is_empty() {
continue;
}
let mut iter = content.split_whitespace(); let mut iter = content.split_whitespace();
let mut next = || iter.next() let mut next = || {
.ok_or_else(|| format_err!("Error while parsing '{}'", path)); iter.next()
.ok_or_else(|| format_err!("Error while parsing '{}'", path))
};
let (dest, prefix) = (next()?, next()?); let (dest, prefix) = (next()?, next()?);
for _ in 0..2 { next()?; } for _ in 0..2 {
next()?;
}
let (nexthop, metric) = (next()?, next()?); let (nexthop, metric) = (next()?, next()?);
for _ in 0..3 { next()?; } for _ in 0..3 {
next()?;
}
let iface = next()?; let iface = next()?;
result.push(ProcFsNetIPv6Route { result.push(ProcFsNetIPv6Route {

View File

@ -14,24 +14,16 @@ use super::try_block;
/// ///
/// This basically call ``std::fs::read``, but provides more elaborate /// This basically call ``std::fs::read``, but provides more elaborate
/// error messages including the path. /// error messages including the path.
pub fn file_get_contents<P: AsRef<Path>>( pub fn file_get_contents<P: AsRef<Path>>(path: P) -> Result<Vec<u8>, Error> {
path: P,
) -> Result<Vec<u8>, Error> {
let path = path.as_ref(); let path = path.as_ref();
std::fs::read(path) std::fs::read(path).map_err(|err| format_err!("unable to read {:?} - {}", path, err))
.map_err(|err| format_err!("unable to read {:?} - {}", path, err))
} }
/// Read .json file into a ``Value`` /// Read .json file into a ``Value``
/// ///
/// The optional ``default`` is used when the file does not exist. /// The optional ``default`` is used when the file does not exist.
pub fn file_get_json<P: AsRef<Path>>( pub fn file_get_json<P: AsRef<Path>>(path: P, default: Option<Value>) -> Result<Value, Error> {
path: P,
default: Option<Value>,
) -> Result<Value, Error> {
let path = path.as_ref(); let path = path.as_ref();
let raw = match std::fs::read(path) { let raw = match std::fs::read(path) {
@ -50,14 +42,12 @@ pub fn file_get_json<P: AsRef<Path>>(
let data = String::from_utf8(raw)?; let data = String::from_utf8(raw)?;
let json = serde_json::from_str(&data)?; let json = serde_json::from_str(&data)?;
Ok(json) Ok(json)
}).map_err(|err: Error| format_err!("unable to parse json from {:?} - {}", path, err)) })
.map_err(|err: Error| format_err!("unable to parse json from {:?} - {}", path, err))
} }
/// Read the first line of a file as String /// Read the first line of a file as String
pub fn file_read_firstline<P: AsRef<Path>>( pub fn file_read_firstline<P: AsRef<Path>>(path: P) -> Result<String, Error> {
path: P,
) -> Result<String, Error> {
let path = path.as_ref(); let path = path.as_ref();
try_block!({ try_block!({
@ -70,7 +60,8 @@ pub fn file_read_firstline<P: AsRef<Path>>(
let _ = reader.read_line(&mut line)?; let _ = reader.read_line(&mut line)?;
Ok(line) Ok(line)
}).map_err(|err: Error| format_err!("unable to read {:?} - {}", path, err)) })
.map_err(|err: Error| format_err!("unable to read {:?} - {}", path, err))
} }
/// Atomically write a file /// Atomically write a file
@ -106,8 +97,7 @@ pub fn file_set_contents_full<P: AsRef<Path>>(
let tmp_path = tmp_path.as_path(); let tmp_path = tmp_path.as_path();
let mode: stat::Mode = perm.unwrap_or(stat::Mode::from( let mode: stat::Mode = perm.unwrap_or(stat::Mode::from(
stat::Mode::S_IRUSR | stat::Mode::S_IWUSR | stat::Mode::S_IRUSR | stat::Mode::S_IWUSR | stat::Mode::S_IRGRP | stat::Mode::S_IROTH,
stat::Mode::S_IRGRP | stat::Mode::S_IROTH
)); ));
if perm != None { if perm != None {
@ -143,14 +133,17 @@ pub fn file_set_contents_full<P: AsRef<Path>>(
pub fn fchown( pub fn fchown(
fd: RawFd, fd: RawFd,
owner: Option<nix::unistd::Uid>, owner: Option<nix::unistd::Uid>,
group: Option<nix::unistd::Gid> group: Option<nix::unistd::Gid>,
) -> Result<(), Error> { ) -> Result<(), Error> {
// According to the POSIX specification, -1 is used to indicate that owner and group // According to the POSIX specification, -1 is used to indicate that owner and group
// are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap // are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap
// around to get -1 (copied fron nix crate). // around to get -1 (copied fron nix crate).
let uid = owner.map(Into::into).unwrap_or((0 as libc::uid_t).wrapping_sub(1)); let uid = owner
let gid = group.map(Into::into).unwrap_or((0 as libc::gid_t).wrapping_sub(1)); .map(Into::into)
.unwrap_or((0 as libc::uid_t).wrapping_sub(1));
let gid = group
.map(Into::into)
.unwrap_or((0 as libc::gid_t).wrapping_sub(1));
let res = unsafe { libc::fchown(fd, uid, gid) }; let res = unsafe { libc::fchown(fd, uid, gid) };
nix::errno::Errno::result(res)?; nix::errno::Errno::result(res)?;
@ -166,17 +159,16 @@ pub fn create_dir_chown<P: AsRef<Path>>(
perm: Option<stat::Mode>, perm: Option<stat::Mode>,
owner: Option<unistd::Uid>, owner: Option<unistd::Uid>,
group: Option<unistd::Gid>, group: Option<unistd::Gid>,
) -> Result<(), nix::Error> ) -> Result<(), nix::Error> {
{
let mode: stat::Mode = perm.unwrap_or(stat::Mode::from_bits_truncate(0o770)); let mode: stat::Mode = perm.unwrap_or(stat::Mode::from_bits_truncate(0o770));
let path = path.as_ref(); let path = path.as_ref();
match nix::unistd::mkdir(path, mode) { match nix::unistd::mkdir(path, mode) {
Ok(()) => {}, Ok(()) => {}
Err(nix::Error::Sys(nix::errno::Errno::EEXIST)) => { Err(nix::Error::Sys(nix::errno::Errno::EEXIST)) => {
return Ok(()); return Ok(());
}, }
err => return err, err => return err,
} }
@ -208,7 +200,9 @@ pub fn image_size(path: &Path) -> Result<u64, Error> {
} else if file_type.is_file() { } else if file_type.is_file() {
Ok(metadata.len()) Ok(metadata.len())
} else { } else {
bail!("image size failed - got unexpected file type {:?}", file_type); bail!(
"image size failed - got unexpected file type {:?}",
file_type
);
} }
} }