use super::{Kind, hash_tree, open_file, process_tree, text};
use crate::{Artifact, fs_safety};
use rayon::prelude::*;
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::{
fs,
io::{self, Read},
path::{Path, PathBuf},
time::Instant,
};
#[derive(Clone, Copy, Default, Serialize)]
struct FileTimes {
files: u64,
bytes: u64,
reads: u64,
open_ns: u64,
handle_metadata_ns: u64,
read_ns: u64,
sha256_ns: u64,
close_ns: u64,
buffer_allocation_ns: u64,
}
impl FileTimes {
fn merge(&mut self, rhs: Self) {
self.files += rhs.files;
self.bytes += rhs.bytes;
self.reads += rhs.reads;
self.open_ns += rhs.open_ns;
self.handle_metadata_ns += rhs.handle_metadata_ns;
self.read_ns += rhs.read_ns;
self.sha256_ns += rhs.sha256_ns;
self.close_ns += rhs.close_ns;
self.buffer_allocation_ns += rhs.buffer_allocation_ns;
}
}
#[derive(Default, Serialize)]
pub struct ContentProfile {
workers: usize,
directories: usize,
listed_entries: usize,
enumeration_wall_ns: u64,
enumerate_ns: u64,
dir_metadata_ns: u64,
sort_ns: u64,
path_ns: u64,
content_wall_ns: u64,
content_work: FileTimes,
checksum: String,
}
fn visit(
path: &Path,
metadata: fs::Metadata,
files: &mut Vec<PathBuf>,
profile: &mut ContentProfile,
) -> io::Result<()> {
if !metadata.is_dir() {
files.push(path.to_owned());
return Ok(());
}
profile.directories += 1;
let start = Instant::now();
let mut children = fs::read_dir(path)?.collect::<io::Result<Vec<_>>>()?;
profile.enumerate_ns += ns(start);
profile.listed_entries += children.len();
let start = Instant::now();
children.sort_unstable_by_key(|entry| entry.file_name());
profile.sort_ns += ns(start);
for child in children {
let start = Instant::now();
let name = child
.file_name()
.into_string()
.map_err(|_| fs_safety::invalid("filename is not Unicode"))?;
fs_safety::relative(&name, false)?;
let child_path = child.path();
profile.path_ns += ns(start);
let start = Instant::now();
let metadata = fs_safety::checked(&child_path, child.metadata()?)?;
profile.dir_metadata_ns += ns(start);
visit(&child_path, metadata, files, profile)?;
}
Ok(())
}
fn ns(start: Instant) -> u64 {
start.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
}
fn read_file(path: &Path, buf: &mut [u8]) -> io::Result<(FileTimes, super::Hash)> {
let mut times = FileTimes {
files: 1,
..FileTimes::default()
};
let start = Instant::now();
let mut file = open_file(path, false)?;
times.open_ns = ns(start);
let start = Instant::now();
if !fs_safety::checked(path, file.metadata()?)?.is_file() {
return Err(fs_safety::invalid("expected regular file"));
}
times.handle_metadata_ns = ns(start);
let mut hash = Sha256::new();
loop {
let start = Instant::now();
let len = file.read(buf)?;
times.read_ns += ns(start);
times.reads += 1;
if len == 0 {
break;
}
times.bytes += len as u64;
let start = Instant::now();
hash.update(&buf[..len]);
times.sha256_ns += ns(start);
}
let start = Instant::now();
let result = hash.finalize().into();
times.sha256_ns += ns(start);
let start = Instant::now();
drop(file);
times.close_ns = ns(start);
Ok((times, result))
}
pub fn profile_content(
root: &Path,
inputs: &[Artifact],
workers: usize,
) -> io::Result<ContentProfile> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(workers)
.build()
.map_err(io::Error::other)?;
let mut profile = ContentProfile {
workers,
..ContentProfile::default()
};
let start = Instant::now();
let mut groups = Vec::new();
for input in inputs {
let target = fs_safety::path(root, &input.path, false)?;
let metadata = fs_safety::node_md(&target)?;
if metadata.is_file() != (input.kind == Kind::File) {
return Err(fs_safety::invalid("input kind changed"));
}
let mut files = Vec::new();
visit(&target, metadata, &mut files, &mut profile)?;
groups.push(files);
}
profile.enumeration_wall_ns = ns(start);
let start = Instant::now();
let mut checksum = Sha256::new();
for files in &groups {
let init = || {
let start = Instant::now();
let buffer = vec![0; 128 * 1024];
(buffer, ns(start))
};
let work = |(buffer, allocation): &mut (Vec<u8>, u64), path: &PathBuf| {
let (mut times, hash) = read_file(path, buffer)?;
times.buffer_allocation_ns = std::mem::take(allocation);
Ok::<_, io::Error>((times, hash))
};
let results = if files.len() >= 64 {
pool.install(|| {
files
.par_iter()
.with_min_len(16)
.map_init(init, work)
.collect::<io::Result<Vec<_>>>()
})?
} else {
let mut state = init();
files
.iter()
.map(|path| work(&mut state, path))
.collect::<io::Result<Vec<_>>>()?
};
for (times, hash) in results {
profile.content_work.merge(times);
checksum.update(hash);
}
}
profile.content_wall_ns = ns(start);
profile.checksum = text(&checksum.finalize().into());
Ok(profile)
}
pub fn exact_content(
root: &Path,
inputs: &[Artifact],
workers: usize,
phase3_reader: bool,
) -> io::Result<serde_json::Value> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(workers)
.build()
.map_err(io::Error::other)?;
let start = Instant::now();
let mut hashing_ns = 0;
let mut manifest_ns = 0;
let mut signature = Sha256::new();
for input in inputs {
let start = Instant::now();
let tree = if phase3_reader {
process_tree(root, input, Some(&pool), |buffer, path| {
let mut file = open_file(path, false)?;
if !fs_safety::checked(path, file.metadata()?)?.is_file() {
return Err(fs_safety::invalid("expected regular file"));
}
let mut hash = Sha256::new();
loop {
let size = file.read(buffer)?;
if size == 0 {
break;
}
hash.update(&buffer[..size]);
}
Ok(hash.finalize().into())
})?
} else {
hash_tree(root, input, Some(&pool))?
};
hashing_ns += ns(start);
let start = Instant::now();
signature.update(serde_json::to_vec(&tree)?);
manifest_ns += ns(start);
}
Ok(serde_json::json!({
"workers": workers, "wall_ns": ns(start), "hashing_ns": hashing_ns,
"manifest_ns": manifest_ns, "tree_sha256": text(&signature.finalize().into()),
"sha_ni": sha_ni()
}))
}
fn sha_ni() -> bool {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
return std::is_x86_feature_detected!("sha");
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
false
}