-
-
Notifications
You must be signed in to change notification settings - Fork 32.1k
gh-81340: Use copy_file_range
in shutil.copyfile
copy functions
#93152
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
985159a
Move determining a block size for copying to a separate function
illia-v e4fa33b
Add copy-on-write support to shutil
illia-v 47b0834
Update comments in `_determine_linux_fastcopy_blocksize`
illia-v 474859c
Update docs to link to `copy_file_range` as a Python function
illia-v 1846895
Merge branch 'main' into fix-issue-81340
illia-v 41d48d9
Drop the `allow_reflink` argument
illia-v e8feaca
Remove duplicate change entries from docs
illia-v dc07a54
Merge branch 'main' into fix-issue-81340
illia-v cb1dae8
Merge branch 'main' into fix-issue-81340
zooba 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 |
---|---|---|
|
@@ -43,6 +43,7 @@ | |
# This should never be removed, see rationale in: | ||
# https://bugs.python.org/issue43743#msg393429 | ||
_USE_CP_SENDFILE = hasattr(os, "sendfile") and sys.platform.startswith("linux") | ||
_USE_CP_COPY_FILE_RANGE = hasattr(os, "copy_file_range") | ||
_HAS_FCOPYFILE = posix and hasattr(posix, "_fcopyfile") # macOS | ||
|
||
# CMD defaults in Windows 10 | ||
|
@@ -103,6 +104,66 @@ def _fastcopy_fcopyfile(fsrc, fdst, flags): | |
else: | ||
raise err from None | ||
|
||
def _determine_linux_fastcopy_blocksize(infd): | ||
"""Determine blocksize for fastcopying on Linux. | ||
|
||
Hopefully the whole file will be copied in a single call. | ||
The copying itself should be performed in a loop 'till EOF is | ||
reached (0 return) so a blocksize smaller or bigger than the actual | ||
file size should not make any difference, also in case the file | ||
content changes while being copied. | ||
""" | ||
try: | ||
blocksize = max(os.fstat(infd).st_size, 2 ** 23) # min 8MiB | ||
except OSError: | ||
blocksize = 2 ** 27 # 128MiB | ||
# On 32-bit architectures truncate to 1GiB to avoid OverflowError, | ||
illia-v marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# see bpo-38319. | ||
illia-v marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if sys.maxsize < 2 ** 32: | ||
blocksize = min(blocksize, 2 ** 30) | ||
return blocksize | ||
|
||
def _fastcopy_copy_file_range(fsrc, fdst): | ||
"""Copy data from one regular mmap-like fd to another by using | ||
a high-performance copy_file_range(2) syscall that gives filesystems | ||
an opportunity to implement the use of reflinks or server-side copy. | ||
|
||
This should work on Linux >= 4.5 only. | ||
""" | ||
try: | ||
infd = fsrc.fileno() | ||
outfd = fdst.fileno() | ||
except Exception as err: | ||
raise _GiveupOnFastCopy(err) # not a regular file | ||
|
||
blocksize = _determine_linux_fastcopy_blocksize(infd) | ||
offset = 0 | ||
while True: | ||
try: | ||
n_copied = os.copy_file_range(infd, outfd, blocksize, offset_dst=offset) | ||
except OSError as err: | ||
# ...in oder to have a more informative exception. | ||
err.filename = fsrc.name | ||
err.filename2 = fdst.name | ||
|
||
if err.errno == errno.ENOSPC: # filesystem is full | ||
raise err from None | ||
|
||
# Give up on first call and if no data was copied. | ||
if offset == 0 and os.lseek(outfd, 0, os.SEEK_CUR) == 0: | ||
raise _GiveupOnFastCopy(err) | ||
|
||
raise err | ||
else: | ||
if n_copied == 0: | ||
# If no bytes have been copied yet, copy_file_range | ||
# might silently fail. | ||
# https://lore.kernel.org/linux-fsdevel/[email protected]/T/#m05753578c7f7882f6e9ffe01f981bc223edef2b0 | ||
if offset == 0: | ||
raise _GiveupOnFastCopy() | ||
barneygale marked this conversation as resolved.
Show resolved
Hide resolved
|
||
break | ||
offset += n_copied | ||
|
||
def _fastcopy_sendfile(fsrc, fdst): | ||
"""Copy data from one regular mmap-like fd to another by using | ||
high-performance sendfile(2) syscall. | ||
|
@@ -124,20 +185,7 @@ def _fastcopy_sendfile(fsrc, fdst): | |
except Exception as err: | ||
raise _GiveupOnFastCopy(err) # not a regular file | ||
|
||
# Hopefully the whole file will be copied in a single call. | ||
# sendfile() is called in a loop 'till EOF is reached (0 return) | ||
# so a bufsize smaller or bigger than the actual file size | ||
# should not make any difference, also in case the file content | ||
# changes while being copied. | ||
try: | ||
blocksize = max(os.fstat(infd).st_size, 2 ** 23) # min 8MiB | ||
except OSError: | ||
blocksize = 2 ** 27 # 128MiB | ||
# On 32-bit architectures truncate to 1GiB to avoid OverflowError, | ||
# see bpo-38319. | ||
if sys.maxsize < 2 ** 32: | ||
blocksize = min(blocksize, 2 ** 30) | ||
|
||
blocksize = _determine_linux_fastcopy_blocksize(infd) | ||
offset = 0 | ||
while True: | ||
try: | ||
|
@@ -224,7 +272,7 @@ def _stat(fn): | |
def _islink(fn): | ||
return fn.is_symlink() if isinstance(fn, os.DirEntry) else os.path.islink(fn) | ||
|
||
def copyfile(src, dst, *, follow_symlinks=True): | ||
def copyfile(src, dst, *, follow_symlinks=True, allow_reflink=True): | ||
"""Copy data from src to dst in the most efficient way possible. | ||
|
||
If follow_symlinks is not set and src is a symbolic link, a new | ||
|
@@ -265,12 +313,20 @@ def copyfile(src, dst, *, follow_symlinks=True): | |
except _GiveupOnFastCopy: | ||
pass | ||
# Linux | ||
elif _USE_CP_SENDFILE: | ||
try: | ||
_fastcopy_sendfile(fsrc, fdst) | ||
return dst | ||
except _GiveupOnFastCopy: | ||
pass | ||
elif _USE_CP_SENDFILE or _USE_CP_COPY_FILE_RANGE: | ||
# reflink may be implicit in copy_file_range. | ||
if _USE_CP_COPY_FILE_RANGE and allow_reflink: | ||
try: | ||
_fastcopy_copy_file_range(fsrc, fdst) | ||
return dst | ||
except _GiveupOnFastCopy: | ||
pass | ||
if _USE_CP_SENDFILE: | ||
try: | ||
_fastcopy_sendfile(fsrc, fdst) | ||
return dst | ||
except _GiveupOnFastCopy: | ||
pass | ||
# Windows, see: | ||
# https://github.com/python/cpython/pull/7160#discussion_r195405230 | ||
elif _WINDOWS and file_size > 0: | ||
|
@@ -403,7 +459,7 @@ def lookup(name): | |
else: | ||
raise | ||
|
||
def copy(src, dst, *, follow_symlinks=True): | ||
def copy(src, dst, *, follow_symlinks=True, allow_reflink=True): | ||
"""Copy data and mode bits ("cp src dst"). Return the file's destination. | ||
|
||
The destination may be a directory. | ||
|
@@ -417,11 +473,11 @@ def copy(src, dst, *, follow_symlinks=True): | |
""" | ||
if os.path.isdir(dst): | ||
dst = os.path.join(dst, os.path.basename(src)) | ||
copyfile(src, dst, follow_symlinks=follow_symlinks) | ||
copyfile(src, dst, follow_symlinks=follow_symlinks, allow_reflink=allow_reflink) | ||
copymode(src, dst, follow_symlinks=follow_symlinks) | ||
return dst | ||
|
||
def copy2(src, dst, *, follow_symlinks=True): | ||
def copy2(src, dst, *, follow_symlinks=True, allow_reflink=True): | ||
"""Copy data and metadata. Return the file's destination. | ||
|
||
Metadata is copied with copystat(). Please see the copystat function | ||
|
@@ -434,7 +490,7 @@ def copy2(src, dst, *, follow_symlinks=True): | |
""" | ||
if os.path.isdir(dst): | ||
dst = os.path.join(dst, os.path.basename(src)) | ||
copyfile(src, dst, follow_symlinks=follow_symlinks) | ||
copyfile(src, dst, follow_symlinks=follow_symlinks, allow_reflink=allow_reflink) | ||
copystat(src, dst, follow_symlinks=follow_symlinks) | ||
return dst | ||
|
||
|
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.
Uh oh!
There was an error while loading. Please reload this page.