-
Notifications
You must be signed in to change notification settings - Fork 86
pipelined extraction #236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
pipelined extraction #236
Conversation
7a45b32
to
5cec332
Compare
Going to try to get this one in before figuring out the cli PR. |
fa18aa3
to
7332eb6
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here's a review of what I've read so far. Still needs a fair bit of work, but I'm happy with the overall concept.
pub file_range_copy_buffer_length: usize, | ||
/// Size of buffer used to splice contents from a pipe into an output file handle. | ||
/// | ||
/// Used on non-Linux platforms without [`splice()`](https://en.wikipedia.org/wiki/Splice_(system_call)). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This buffer isn't necessary on any Unix; see https://stackoverflow.com/a/10330172.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure I understand your meaning here. That answer seems to say that on non-linux platforms, read()
/write()
with an explicit buffer (as we do here) is the way to go. Our PipeReadBufferSplicer
struct performs read()
then pwrite_all()
with an explicit buffer, because we can't use splice()
.
Do I misunderstand you here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What it's saying is that on Unix, when you don't have splice()
you should memmap()
the file directly and pass the mapped region to write()
. The memmap2
crate will provide the wrapper we need.
thank you so much for these wonderful comments!! |
15c3ef5
to
6f9d3d6
Compare
Was able to remove the |
Hey @Pr0methean -- think I got to all of your comments! I proposed a couple compromises to do in follow-up PRs (supporting absolute extraction paths and symlinks)--let me know if you agree! I am hoping to spend more time on this in the next few weeks to get it in and then do the follow-ups. No rush as usual, and I really appreciate your comments. |
|
||
let params = ExtractionParameters { | ||
decompression_threads: DECOMPRESSION_THREADS, | ||
decompression_threads: num_cpus::get() / 3, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What will the other 2/3 of the CPUs be doing? Also, does this need to be clamped to at least 1?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good; just 2 minor comments.
let block = Self::from_le(block); | ||
/// Convert endianness and check the magic value. | ||
#[allow(clippy::wrong_self_convention)] | ||
fn validate(self) -> ZipResult<Self> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Call this function from_le_validated
to make its combined functionality more clear, or separate out the from_le
call and call it with_checked_magic
.
Hey, I'm going to work on this again. A friend just mentioned to me making temporary files for outputs instead of creating the entire output directory hierarchy upfront and that solved the issue that was blocking me. I'm also going to close the massive |
There was also an additional very tricky concern about preserving permissions of the output directory (a concern shared with the default extract method). I don't think that's immediately solved, but performing the extraction in a temp directory should at least move the perms calculation off the critical path. In fact, it might be appropriate to only expose an API that extracts into a temp dir, and then separately sync that temp dir with the real dir. This would likely be nicer for invocations from an async context, minimizing the amount of blocking work done at a time. It would be really nice if coroutines were stable. |
- initial sketch of lexicographic trie for pipelining - move path splitting into a submodule - lex trie can now propagate entry data - outline handle allocation - mostly handle files - mostly handle dirs - clarify symlink FIXMEs - do symlink validation - extract writable dir setting to helper method - modify args to handle allocation method - handle allocation test passes - simplify perms a lot - outline evaluation - handle symlinks - BIGGER CHANGE! add EntryReader/etc - make initial pipelined extract work - fix file perms by writing them after finishing the file write - support directory entries by unix mode as well - impl split extraction - remove dependency on reader refactoring - add dead_code to methods we don't use yet - bzip2 support needed for benchmark test - correctly handle backslashes in entry names (i.e. don't) - make PathSplitError avoid consing a String until necessary - add repro_old423 test for pipelining - silence dead code warnings for windows - avoid erroring for top-level directory entries - use num_cpus by default for parallelism - we spawn three threads per chunk - add dynamically-generated test archive - initialize the test archives exactly once in statics - add benchmarks for dynamic and static test data - use lazy_static - add FIXME for follow-up work to support absolute paths - impl From<DirEntry<...>> for FSEntry - move handle_creation module to a separate file - downgrade HandleCreationError to io::Error - use ByAddress over ZipDataHandle - replace unsafe transmutes with Pod methods - add note about shared future dependency task DAG - box each level of the b-tree together with its values this may technically reduce heap fragmentation, but since this data structure only exists temporarily, that's probably not too important. instead, this change just reduces the amount of coercion and unboxing we need to do
5d69fc0
to
f3fee69
Compare
It should be up to date now. Thanks again for all your efforts in the meantime to keep this alive. I am pretty sure the temp files and temp dir technique should overcome the blockers and reduce a lot of the complexity in the pipelining setup (not to mention improved perf, etc). The biggest difficulty I'd had was around symlinks and output files which may be in paths defined by symlinks. Semantic Differences with Serial Path ConstructionThere is an (easy) semantic decision to make here. Traditional serial extraction would error if an entry name earlier on went through a symlink that was only defined later. I don't think it's likely anyone is relying upon that failure mode for correctness, and rather I suspect people are getting surprised by that failure mode in the serial case. So I think it's safe to apply the symlinks all at once, before assigning output file handles to paths in the output temp dir, and alleviate that failure mode once and for all. A reasonable question to ask is whether we'd want to do the same for our simple serial extraction--I would say not in this PR, and possibly not at all (there is a benefit to having an extremely simple and easy-to-audit serial extraction loop). For example in Applications of this Work and Follow-UpOn the subject of "experimental": I have at least mentioned this parallel zip mechanism in the context of Python packaging standards (https://discuss.python.org/t/pep-777-how-to-re-invent-the-wheel/67484/243), and I will be using this technique in a prototype Python package indexer/fetcher tool I'm working on (which will be in Rust and depend upon the Eventually: Breaking Out POSIX API wrappersPython happens to have a lot more than Rust provided in the stdlib (particularly I know one (linux-specific) OS call we couldn't use in this PR was Either before or after said follow-up PR, I think breaking out a separate crate for various POSIX fs and i/o wrappers might be useful, especially given discussions like this https://internals.rust-lang.org/t/why-no-fork-in-std-process/13770 flatly rejecting None of this should be relevant to this PR (which I'll get back to momentarily), but I'll probably end up producing a POSIX-specific Windows / in-memory ring buffer / pipelined streaming extractionI don't have a Windows machine to test on, but I think this approach should be extensible to Windows by using an in-process blocking ring buffer instead of an OS pipe. When I looked for such a data structure on crates.io, I couldn't actually find it, and I avoided implementing it here because the code was already getting unwieldy. But such an in-memory approach would be applicable to e.g. I think this in-memory ring buffer could just use a mutex + condvar, since blocking is exactly what we want it to do when starved. That's kind of interesting, especially since avoiding OS pipes would mean we could pipe the decompressed output (or even compressed) into an arbitrary It's beginning to seem like using the linux-specific syscalls might have obscured this simpler approach the whole time. Sure, |
Very lengthy and meandering comment above, but with the significant realization at the end that an in-memory (fixed-size, maybe growable) ring buffer that blocks when empty would likely have been easy enough to slap together without any low-level atomic operations (just mutex + cvar), would work on all platforms and i/o sources, and in general seems like a much cleaner architecture. I think the Especially given that we also just realized that much of the scheduling work is likely obsolete now too (after realizing that we should use temp output files and a temp output dir), I'm actually thinking of letting this PR sit for a bit now (in case I've made a mistake in the above reasoning), and switching over to #235 instead. |
Getting more excited about this and I don't know if I'll be in steady communication the whole time but I think this would be highly auditable and highly performant and I live for that sort of thing. Going to spend some time this weekend on it. |
Would like to note that the python tool This incident from
Given that we have also found above that temporary files can be used to avoid allocating output handles upfront, I think these can both be covered by a similar abstraction, which performs the following:
For network or stdin streams, this will unblock later entries from an especially-large and highly-compressed intermediate entry (which was the reason we needed It remains to be seen whether we'll need to incorporate I'm thinking the way to get this into a minimal PR that can be incorporated into the rest of the crate would be to start off with the most general approach, and avoid
My hope is actually that these can be expressed in terms of the Will be spending more time today on this approach. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wow, this is coming along really well!
* - 200K random data, stored uncompressed (CompressionMethod::Stored) | ||
* - 246K text data (the project gutenberg html version of king lear) | ||
* (CompressionMethod::Bzip2, compression level 1) (project gutenberg ebooks are public domain) | ||
* |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we include some compressed files that contain both text and random bytes, to reflect the fact that real files tend to have sections with different entropy rates (e.g. image content vs metadata)?
* The full archive file is 5.3MB. | ||
*/ | ||
fn static_test_archive() -> ZipResult<ZipArchive<fs::File>> { | ||
assert!( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use a #cfg
attribute instead so that this check can happen at build time.
* dependencies and schedule the symlink dereference (reading the target value from the zip) | ||
* before we create any directories or allocate any output file handles that dereference that | ||
* symlink. This is less of a problem with the synchronous in-order extraction because it | ||
* creates any symlinks immediately (it imposes a total ordering dependency over all entries). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think (2) is a problem, because symlinks to nonexistent targets can be part of a valid archive.
* complex platform-specific programming. However, the result would likely decrease the | ||
* number of syscalls, which may also improve performance. It may also be slightly easier to | ||
* follow the logic if we can refer to directory inodes instead of constructing path strings | ||
* as a proxy. This should be considered if requested by users. */ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems out of scope - if users need that functionality, then they probably also need it for purposes that don't involve zip files, so either the create_dir_all
implementation should be changed or a file-management crate's replacement for create_dir_all
should be used.
perms_todo.push((path.clone(), fs::Permissions::from_mode(mode))); | ||
} | ||
|
||
let handle = fs::OpenOptions::new() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull the OpenOptions
out into a variable and reuse it.
} | ||
|
||
pub(crate) trait DirByMode { | ||
fn is_dir_by_mode(&self) -> bool; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make this part of impl ZipFileData
instead, since no other implementation of DirByMode
exists outside of tests.
} | ||
|
||
#[derive(PartialEq, Eq, Debug, Clone)] | ||
pub(crate) enum FSEntry<'a, Data> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like this could really use methods #[cfg(test)] add_file(&mut self, name: &str)
and #[cfg(test)] add_subdirectory(&mut self, name: &str)
($op:expr) => { | ||
match $op { | ||
Ok(n) => n, | ||
Err(e) if e.kind() == ::std::io::ErrorKind::Interrupted => continue, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems like the wrong behavior; shouldn't we generally break out of the loop and return an error when interrupted?
use std::mem::MaybeUninit; | ||
use std::ops; | ||
|
||
pub trait FixedFile { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ambiguous name. "Fixed" in the sense of "immutable" or "corrected"? Could something like KnownSizeFile
be used instead?
let block = Self::from_le(block); | ||
/// Convert endianness and check the magic value. | ||
#[allow(clippy::wrong_self_convention)] | ||
fn validate(self) -> ZipResult<Self> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A name like try_from_le
or valid_from_le
would make it clearer that this includes the endian conversion.
Recreation of #208 to work around github issues.
Problem
ZipArchive::extract()
corresponds to the way most zip implementations perform the task, but it's single-threaded. This is appropriate under the assumptions imposed by rust'sRead
andSeek
traits, where mutable access is necessary and only one reader can extract file contents at a time, but most unix-like operating systems offer apread()
operation which avoids mutating OS state like the file offset, so multiple threads can read from a file handle at once. The go programming language offersio.ReaderAt
in the stdlib to codify this ability.Solution
This is a rework of #72 which avoids introducing unnecessary thread pools and creates all output file handles and containing directories up front. For large zips, we want to:
src/read/split.rs
was created to coverpread()
and other operations, whilesrc/read/pipelining.rs
was created to perform the high-level logic to split up entries and perform pipelined extraction.Result
parallelism
feature was added to the crate to gate the newly added code + API.libc
crate was added for#[cfg(all(unix, feature = "parallelism"))]
in order to make use of OS-specific functionality.zip::read::split_extract()
was added as a new external API to extract&ZipArchive<fs::File>
when#[cfg(all(unix, feature = "parallelism"))]
.Note that this does not handle symlinks yet, which I plan to add in a followup PR.
CURRENT BENCHMARK STATUS
On a linux host (with
splice()
and optionallycopy_file_range()
), we get about a 6.5x speedup with 12 decompression threads:The performance should keep increasing as we increase thread count, up to the number of available CPU cores (this was running with a parallelism of 12 on my 16-core laptop). This also works on macOS and BSDs, and other
#[cfg(unix)]
platforms.