-
Notifications
You must be signed in to change notification settings - Fork 985
Lock download file to avoid races #4606
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
Open
konstin
wants to merge
3
commits into
rust-lang:main
Choose a base branch
from
konstin:konsti/lock-downloads
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+113
−13
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,9 @@ | ||
| //! Easy file downloading | ||
|
|
||
| use std::fs::remove_file; | ||
| use std::fs::{File, OpenOptions, remove_file}; | ||
| use std::io; | ||
| use std::num::NonZero; | ||
| use std::path::Path; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::str::FromStr; | ||
| use std::time::Duration; | ||
|
|
||
|
|
@@ -26,6 +27,96 @@ use crate::{dist::download::DownloadStatus, errors::RustupError, process::Proces | |
| #[cfg(test)] | ||
| mod tests; | ||
|
|
||
| /// An OS lock on a file that unlocks when dropping the file. | ||
| pub(crate) struct LockedFile { | ||
| path: PathBuf, | ||
| file: File, | ||
| } | ||
|
|
||
| impl LockedFile { | ||
| /// Creates the file if it does not exit, does not lock. | ||
| #[cfg(unix)] | ||
| pub(crate) fn create(path: impl Into<PathBuf>) -> Result<Self, io::Error> { | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use tempfile::NamedTempFile; | ||
|
|
||
| let path = path.into(); | ||
|
|
||
| // If path already exists, return it. | ||
| if let Ok(file) = OpenOptions::new().read(true).write(true).open(&path) { | ||
| return Ok(Self { path, file }); | ||
| } | ||
|
|
||
| // Otherwise, create a temporary file with 777 permissions, to handle races between | ||
| // processes running under different UIDs (e.g., in Docker containers). We must set | ||
| // permissions _after_ creating the file, to override the `umask`. | ||
| let file = if let Some(parent) = path.parent() { | ||
| NamedTempFile::new_in(parent)? | ||
| } else { | ||
| NamedTempFile::new()? | ||
| }; | ||
| if let Err(err) = file | ||
| .as_file() | ||
| .set_permissions(std::fs::Permissions::from_mode(0o777)) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can the permissions be cached in a static variable?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The method is a no-op constructor. |
||
| { | ||
| warn!("failed to set permissions on temporary file: {err}"); | ||
| } | ||
|
|
||
| // Try to move the file to path, but if path exists now, just open path | ||
| match file.persist_noclobber(&path) { | ||
| Ok(file) => Ok(Self { path, file }), | ||
| Err(err) => { | ||
| if err.error.kind() == io::ErrorKind::AlreadyExists { | ||
| let file = OpenOptions::new().read(true).write(true).open(&path)?; | ||
| Ok(Self { path, file }) | ||
| } else { | ||
| Err(err.error) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Creates the file if it does not exit, does not lock. | ||
| #[cfg(not(unix))] | ||
| pub(crate) fn create(path: impl Into<PathBuf>) -> Result<Self, io::Error> { | ||
| let path = path.into(); | ||
| let file = OpenOptions::new() | ||
| .read(true) | ||
| .write(true) | ||
| .create(true) | ||
| .truncate(true) | ||
| .open(&path)?; | ||
| Ok(Self { path, file }) | ||
| } | ||
|
|
||
| /// Acquire an exclusive lock on a file, blocking until the file is ready. | ||
| pub(crate) fn lock(self) -> Result<Self, io::Error> { | ||
| match self.file.lock() { | ||
| Err(err) if err.kind() == io::ErrorKind::Unsupported => { | ||
| warn!("locking files is not supported, running rustup in parallel may error"); | ||
| Ok(self) | ||
| } | ||
| Err(err) => Err(err), | ||
| Ok(()) => Ok(self), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Drop for LockedFile { | ||
| /// Unlock the file. | ||
| fn drop(&mut self) { | ||
| if let Err(err) = self.file.unlock() { | ||
| warn!( | ||
| "failed to unlock {}; program may be stuck: {}", | ||
| self.path.display(), | ||
| err | ||
| ); | ||
| } else { | ||
| debug!("released lock at `{}`", self.path.display()); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| pub(crate) async fn download_file( | ||
| url: &Url, | ||
| path: &Path, | ||
|
|
@@ -48,7 +139,7 @@ pub(crate) async fn download_file_with_resume( | |
| match download_file_(url, path, hasher, resume_from_partial, status, process).await { | ||
| Ok(_) => Ok(()), | ||
| Err(e) => { | ||
| if e.downcast_ref::<std::io::Error>().is_some() { | ||
| if e.downcast_ref::<io::Error>().is_some() { | ||
| return Err(e); | ||
| } | ||
| let is_client_error = match e.downcast_ref::<DEK>() { | ||
|
|
@@ -722,7 +813,7 @@ enum DownloadError { | |
| #[error("{0}")] | ||
| Message(String), | ||
| #[error(transparent)] | ||
| IoError(#[from] std::io::Error), | ||
| IoError(#[from] io::Error), | ||
| #[cfg(any(feature = "reqwest-rustls-tls", feature = "reqwest-native-tls"))] | ||
| #[error(transparent)] | ||
| Reqwest(#[from] ::reqwest::Error), | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Interesting. I guess Cargo's file locks also have the same issue?