diff --git a/strata_control/transfer.py b/strata_control/transfer.py index 00980ea450..0b10f958d6 100644 --- a/strata_control/transfer.py +++ b/strata_control/transfer.py @@ -20,6 +20,7 @@ import threading import time import email.utils import datetime as _dt +import errno import urllib.error import urllib.parse import urllib.request @@ -33,6 +34,15 @@ tls.install() # #3722: the operating system's certificates, like the browse CHUNK = 1 << 20 WAITED_S = 0.002 # a read that took longer than this had to wait for the server +# errors on the DESTINATION (the .part file) that waiting cannot cure: raised at once, as before the network rule, never retried +# (a full disk, a quota, a read-only drive, no permission); any other write error (EIO on a flaky drive, a share that drops) is retried +_DEST_ERRNOS = {e for e in (errno.ENOSPC, getattr(errno, "EDQUOT", None), errno.EROFS, errno.EACCES, errno.EPERM) if e is not None} +_DEST_OPEN_ERRORS = (PermissionError, IsADirectoryError, NotADirectoryError, FileNotFoundError) + + +def _destination(exc: BaseException) -> BaseException: + exc.strata_destination = True # read in _transfer: a plain TransferError, not an Interrupted + return exc SMALL_LIMIT = 8 << 20 ENV_ALLOW_HTTP = "STRATA_UPDATE_ALLOW_HTTP" @@ -338,9 +348,11 @@ def _transfer(location, partial: Path, have: int, size: int, progress, cancel, t raise TransferError(tls.explain(tls.host_of(location)), resumable=True) from None got = partial.stat().st_size if partial.exists() else 0 reason = getattr(exc, "reason", exc) - raise Interrupted(f"the download of {location} was interrupted after {got} of {size} bytes " - f"({type(exc).__name__}: {reason}); the partial file is kept and the next try resumes it", - resumable=True) from None + said = (f"the download of {location} was interrupted after {got} of {size} bytes " + f"({type(exc).__name__}: {reason}); the partial file is kept and the next try resumes it") + if getattr(exc, "strata_destination", False): # the .part cannot be written (a full disk, no permission): at once, as before + raise TransferError(said, resumable=True) from None + raise Interrupted(said, resumable=True) from None _CONTENT_RANGE = re.compile(r"\s*bytes (\d+)-(\d+)/(\d+|\*)\s*$") @@ -359,33 +371,53 @@ def _copy(source, partial: Path, mode: str, done: int, size: int, progress, canc to wait; when the connection stalls, the bytes gathered so far are written before the error goes on, so the next try resumes after them and the network rule's 5 minutes without a NEW byte are counted on the file's size (strata_control/netpolicy.py).""" read = getattr(source, "read1", None) or source.read - with partial.open(mode) as out: - while True: - if cancel is not None and cancel.is_set(): - out.flush() - raise Cancelled() - gathered = bytearray() - end = False - try: - while len(gathered) < CHUNK: - began = time.monotonic() - piece = read(CHUNK - len(gathered)) - if not piece: - end = True - break - gathered += piece - if time.monotonic() - began > WAITED_S: - break # this read waited for the server: do not hold what we have any longer - except BaseException: - out.write(gathered) # a stall or a break: what did arrive stays on disk - raise - if gathered: - if done + len(gathered) > size: - raise TransferError("the server sent more bytes than the feed says; the download was stopped") - out.write(gathered) - done += len(gathered) - if progress: - progress(done, size) - if end: - break - out.flush() + try: + opened = partial.open(mode) + except _DEST_OPEN_ERRORS as exc: # the .part cannot be written here at all + raise _destination(exc) + + def put(out, data) -> None: + try: + out.write(data) + except OSError as exc: + if exc.errno in _DEST_ERRNOS: + _destination(exc) + raise + + source_failed = False + try: + with opened as out: + while True: + if cancel is not None and cancel.is_set(): + out.flush() + raise Cancelled() + gathered = bytearray() + end = False + try: + while len(gathered) < CHUNK: + began = time.monotonic() + piece = read(CHUNK - len(gathered)) + if not piece: + end = True + break + gathered += piece + if time.monotonic() - began > WAITED_S: + break # this read waited for the server: do not hold what we have any longer + except BaseException: + source_failed = True + put(out, gathered) # a stall or a break: what did arrive stays on disk + raise + if gathered: + if done + len(gathered) > size: + raise TransferError("the server sent more bytes than the feed says; the download was stopped") + put(out, gathered) + done += len(gathered) + if progress: + progress(done, size) + if end: + break + out.flush() + except OSError as exc: # a buffered write fails at flush or close: the same rule + if not source_failed and exc.errno in _DEST_ERRNOS: + _destination(exc) + raise diff --git a/tests/terminal/test_net_transfer.py b/tests/terminal/test_net_transfer.py index ad293e5144..222c6a6aab 100644 --- a/tests/terminal/test_net_transfer.py +++ b/tests/terminal/test_net_transfer.py @@ -243,5 +243,90 @@ class LocalSource(Scaled): self.assertEqual(calls, [("wb", 0), ("ab", 3000)], "one more copy, from the byte the first one reached: no byte twice") +class Destination(Scaled): + """The .part file cannot be written (no permission, a full disk, a quota, a read-only drive): raised at once with the TransferError and words + it had before the network rule ("... (PermissionError: ...)" / "(OSError: [Errno 28] No space left on device)"), not retried for 5 minutes; + what was written stays, so freeing the space and fetching again resumes it.""" + + def fast_failure(self, url): + t0 = time.monotonic() + with self.assertRaises(transfer.TransferError) as cm: + self.fetch(url) + self.assertLess(time.monotonic() - t0, 1.0) + self.assertIs(type(cm.exception), transfer.TransferError, "a plain TransferError, as before: not an Interrupted that is retried") + self.assertTrue(cm.exception.resumable) + self.assertTrue(str(cm.exception).endswith("); the partial file is kept and the next try resumes it"), str(cm.exception)) + return str(cm.exception) + + def test_a_part_file_that_may_not_be_opened_fails_at_once(self): + source = self.dir / "source.bin" + source.write_bytes(BODY) + real_open = Path.open + + def no_part(path, *a, **k): + if path.name == "f.part": + raise PermissionError(13, "Permission denied", str(path)) + return real_open(path, *a, **k) + + with mock.patch.object(Path, "open", no_part): + said = self.fast_failure(str(source)) + self.assertIn("after 0 of 10240 bytes (PermissionError: [Errno 13] Permission denied: ", said) + self.assertFalse((self.dir / "f.part").exists()) + + @unittest.skipUnless(os.name == "posix" and hasattr(os, "geteuid") and os.geteuid() != 0, "a folder without write permission: POSIX, not root") + def test_a_folder_without_write_permission_fails_at_once(self): + source = self.dir / "source.bin" + source.write_bytes(BODY) + locked = self.dir / "locked" + locked.mkdir() + locked.chmod(0o500) + self.addCleanup(locked.chmod, 0o700) + t0 = time.monotonic() + with self.assertRaises(transfer.TransferError) as cm: + transfer.download(str(source), locked / "f.part", size=len(BODY), sha256=SHA) + self.assertLess(time.monotonic() - t0, 1.0) + self.assertIs(type(cm.exception), transfer.TransferError) + self.assertIn("(PermissionError: [Errno 13] Permission denied: ", str(cm.exception)) + self.assertFalse((locked / "f.part").exists()) + + def test_a_full_disk_fails_at_once_keeps_what_was_written_and_resumes_once_there_is_room(self): + behave, st = ranged(chunk=2000, every=0.01) + srv = Server(behave) + self.addCleanup(srv.close) + real_open = Path.open + + class Full: # the disk takes the first write, then: no space left + def __init__(self, f): + self.f, self.n = f, 0 + + def write(self, data): + if self.n: + raise OSError(28, "No space left on device") + self.n += len(data) + return self.f.write(data) + + def flush(self): + self.f.flush() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.f.close() + + def full_part(path, *a, **k): + f = real_open(path, *a, **k) + return Full(f) if path.name == "f.part" else f + + with mock.patch.object(Path, "open", full_part): + said = self.fast_failure(srv.url("/e")) + kept = (self.dir / "f.part").read_bytes() + self.assertTrue(0 < len(kept) < len(BODY), len(kept)) + self.assertEqual(kept, BODY[:len(kept)], "what was written is kept") + self.assertIn(f"after {len(kept)} of 10240 bytes (OSError: [Errno 28] No space left on device)", said) + self.assertEqual(self.fetch(srv.url("/e")).read_bytes(), BODY) # room again: the next try resumes + self.assertEqual(st["ranges"][-1], f"bytes={len(kept)}-") + + if __name__ == "__main__": unittest.main()