okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main c1ff07f1a into f-own-intfefaa985c

main
23.3 KiB441 linesraw
1"""Lane NET item 2: the update path's downloads (strata_control/transfer.py: the engine, the shape engine, Control, the app, DFlash2, the picture
2reader) and the feed read under the network rule, against local servers: a black hole fails fast with the plain sentence; a connection that breaks
3after bytes came is resumed; a link that trickles is never cut; 5 minutes (scaled) without a new byte ends it with W6. The real-time proof (bytes every
420-50 s for 365 s, the rule's own 60 s stall) runs with STRATA_SLOW_NET_TESTS=1."""
5
6from __future__ import annotations
7
8import errno
9import hashlib
10import os
11import tempfile
12import threading
13import time
14import unittest
15import urllib.request
16from pathlib import Path
17from unittest import mock
18
19from strata_control import feed, netpolicy, transfer
20from tests.terminal.test_netpolicy import AT_ONCE_S, REFUSED_WINDOW, BlackHole, Server, refused_port
21
22BODY = bytes(range(256)) * 40          # 10,240 bytes
23SHA = hashlib.sha256(BODY).hexdigest()
24
25
26def ranged(cut_first=None, every=0.0, chunk=None, silent_after=None):
27    """An HTTP file server with Range: `cut_first` bytes then the connection is closed on the first request; `every` seconds between
28    `chunk`-byte writes; `silent_after`: after that many bytes the server stops sending (keeps the connection)."""
29    state = {"n": 0, "ranges": []}                    # "ranges": the Range header of every request, in order
30
31    def behave(h, n):
32        state["n"] += 1
33        start = 0
34        rng = h.headers.get("Range")
35        state["ranges"].append(rng)
36        if rng:
37            start = int(rng.split("=")[1].split("-")[0])
38        body = BODY[start:]
39        h.send_response(206 if rng else 200)
40        if rng:
41            h.send_header("Content-Range", f"bytes {start}-{len(BODY) - 1}/{len(BODY)}")
42        h.send_header("Content-Length", str(len(body)))
43        h.end_headers()
44        if h.command == "HEAD":
45            return
46        limit = cut_first if (cut_first is not None and state["n"] == 1) else len(body)
47        step = chunk or len(body)
48        sent = 0
49        while sent < min(limit, len(body)):
50            if silent_after is not None and start + sent >= silent_after:
51                time.sleep(30)
52                return
53            piece = body[sent:min(sent + step, limit)]
54            try:
55                h.wfile.write(piece)
56                h.wfile.flush()
57            except OSError:
58                return
59            sent += len(piece)
60            if every:
61                time.sleep(every)
62        if limit < len(body):
63            h.close_connection = True
64    return behave, state
65
66
67class Scaled(unittest.TestCase):
68    def setUp(self):
69        for p in (mock.patch.object(netpolicy, "CONNECT_LIMITS", (0.4, 0.8)), mock.patch.object(netpolicy, "RETRY_GAP_S", 0.05),
70                  mock.patch.object(netpolicy, "HOSTS", netpolicy.HostMemory()),
71                  mock.patch.object(transfer, "_opener", netpolicy.build_opener(urllib.request.ProxyHandler({}), transfer._PolicyRedirects))):
72            p.start()
73            self.addCleanup(p.stop)
74        t = tempfile.TemporaryDirectory(prefix="strata-nettransfer-")
75        self.addCleanup(t.cleanup)
76        self.dir = Path(t.name)
77
78    def fetch(self, url, **kw):
79        return transfer.download(url, self.dir / "f.part", size=len(BODY), sha256=SHA, **kw)
80
81
82class TransferRule(Scaled):
83    def test_a_black_hole_fails_fast_with_the_plain_sentence(self):
84        hole = BlackHole()
85        self.addCleanup(hole.close)
86        lines = []
87        t0 = time.monotonic()
88        with mock.patch.object(netpolicy, "WAIT_LINE_AFTER_S", 0.2), mock.patch.object(netpolicy, "WAIT_LINE_EVERY_S", 0.3):
89            with self.assertRaises(transfer.Unreachable) as cm:
90                self.fetch(f"http://127.0.0.1:{hole.port}/e.tar.gz", what="the engine 0.1.59 (cuda)", say=lines.append)
91        self.assertLess(time.monotonic() - t0, 2.5)
92        self.assertTrue(str(cm.exception).startswith("127.0.0.1 did not answer within 1 seconds, so the engine 0.1.59 (cuda) could not be downloaded. "
93                                                     "Check that this computer can open https://127.0.0.1"), str(cm.exception))
94        self.assertTrue(lines and lines[0].startswith("Waiting for 127.0.0.1 to answer ("), lines)
95
96    def test_a_refused_port_fails_at_once(self):
97        t0 = time.monotonic()
98        with mock.patch.object(netpolicy, "CONNECT_LIMITS", REFUSED_WINDOW), self.assertRaises(transfer.Unreachable) as cm:
99            self.fetch(f"http://127.0.0.1:{refused_port()}/e.tar.gz")
100        self.assertLess(time.monotonic() - t0, AT_ONCE_S)
101        self.assertEqual(cm.exception.failure.kind, "offline")
102
103    def test_a_working_download(self):
104        behave, _st = ranged()
105        srv = Server(behave)
106        self.addCleanup(srv.close)
107        self.assertEqual(self.fetch(srv.url("/e")).read_bytes(), BODY)
108
109    def test_a_connection_that_breaks_after_bytes_came_is_resumed_in_the_same_run(self):
110        behave, st = ranged(cut_first=3000)
111        srv = Server(behave)
112        self.addCleanup(srv.close)
113        self.assertEqual(self.fetch(srv.url("/e")).read_bytes(), BODY)       # (the whole file's SHA-256 is checked by download())
114        self.assertEqual(st["ranges"], [None, "bytes=3000-"], "exactly one more request, from the byte the cut reached: no byte twice")
115
116    def test_a_trickle_is_never_cut(self):
117        behave, _st = ranged(every=0.15, chunk=512)                # 20 writes, 3 s in all, each gap far under the stall time
118        srv = Server(behave)
119        self.addCleanup(srv.close)
120        with mock.patch.object(netpolicy, "GIVE_UP_S", 1.0):
121            self.assertEqual(self.fetch(srv.url("/e"), timeout=1.0).read_bytes(), BODY)
122
123    def test_five_minutes_without_a_byte_end_the_download_with_w6(self):
124        behave, _st = ranged(silent_after=5120, chunk=1024)       # half the file, then nothing (the connection stays open)
125        srv = Server(behave)
126        self.addCleanup(srv.close)
127        with mock.patch.object(netpolicy, "GIVE_UP_S", 1.5):
128            t0 = time.monotonic()
129            with self.assertRaises(transfer.TransferError) as cm:
130                self.fetch(srv.url("/e"), timeout=0.4, what="the engine 0.1.59 (cuda)")
131        self.assertLess(time.monotonic() - t0, 6)
132        self.assertEqual(str(cm.exception), "No data arrived for 1 minutes, so the download of the engine 0.1.59 (cuda) stopped at 50%. "
133                                            "Run the same command again: it continues where it stopped.")
134        self.assertTrue(cm.exception.resumable)
135        self.assertEqual((self.dir / "f.part").stat().st_size, 5120)
136        # the next run (a server that now answers) continues from the kept size: one request with the header "Range: bytes=5120-", the whole file's hash is checked
137        again, st2 = ranged()
138        srv2 = Server(again)
139        self.addCleanup(srv2.close)
140        self.assertEqual(self.fetch(srv2.url("/e")).read_bytes(), BODY)
141        self.assertEqual(st2["ranges"], ["bytes=5120-"])
142
143    @unittest.skipUnless(os.environ.get("STRATA_SLOW_NET_TESTS") == "1", "real-time: STRATA_SLOW_NET_TESTS=1")
144    def test_real_time_trickle_for_more_than_five_minutes_with_the_rules_own_numbers(self):
145        """A few bytes every 20-50 s for 365 s, STALL_S 60 and GIVE_UP_S 300 as shipped: the slow link that works is not cut."""
146        gaps = [20, 35, 50, 25, 45, 30, 50, 40, 20, 50]
147        data = b"abcdefgh" * len(gaps)
148        sha = hashlib.sha256(data).hexdigest()
149
150        def behave(h, n):
151            h.send_response(200)
152            h.send_header("Content-Length", str(len(data)))
153            h.end_headers()
154            for i, g in enumerate(gaps):
155                time.sleep(g)
156                h.wfile.write(data[8 * i:8 * i + 8])
157                h.wfile.flush()
158        srv = Server(behave)
159        self.addCleanup(srv.close)
160        t0 = time.monotonic()
161        with mock.patch.object(netpolicy, "CONNECT_LIMITS", (netpolicy.FIRST_CONNECT_S, netpolicy.RETRY_CONNECT_S)):
162            got = transfer.download(srv.url("/slow"), self.dir / "slow.part", size=len(data), sha256=sha)
163        self.assertEqual(got.read_bytes(), data)
164        self.assertGreater(time.monotonic() - t0, 360)
165
166
167class FeedRule(Scaled):
168    def test_a_feed_server_that_does_not_answer_says_w7(self):
169        hole = BlackHole()
170        self.addCleanup(hole.close)
171        with mock.patch.object(transfer, "FIRST_TRY_SECONDS", 0.4):
172            with self.assertRaises(feed.FeedError) as cm:
173                feed.fetch(f"http://127.0.0.1:{hole.port}/strata-feed.json", {"k": b"x" * 32}, timeout=0.8)
174        self.assertEqual(str(cm.exception), "127.0.0.1 did not answer within 1 seconds, so the update check could not run. Check that this computer "
175                                            "can open https://127.0.0.1, then try again. Strata keeps working with what is installed.")
176        t0 = time.monotonic()                                       # the same run asks again: no second wait
177        with self.assertRaises(feed.FeedError) as cm:
178            feed.fetch(f"http://127.0.0.1:{hole.port}/strata-feed.json", {"k": b"x" * 32}, timeout=0.8)
179        self.assertLess(time.monotonic() - t0, 0.2)
180        self.assertEqual(str(cm.exception), "127.0.0.1 did not answer a moment ago, so the update check was not tried again. "
181                                            "Strata keeps working with what is installed.")
182
183    def test_an_offline_computer_gets_the_answer_at_once(self):
184        t0 = time.monotonic()
185        with self.assertRaises(feed.FeedError) as cm:
186            feed.fetch(f"http://127.0.0.1:{refused_port()}/strata-feed.json", {"k": b"x" * 32}, timeout=30)
187        self.assertLess(time.monotonic() - t0, AT_ONCE_S)           # no wait and no retry for an offline user (owner 11-01)
188        self.assertEqual(str(cm.exception), "this computer could not connect to 127.0.0.1 (it looks offline), so the update check could not run. "
189                                            "Strata keeps working with what is installed.")
190
191
192class LocalSource(Scaled):
193    """A local source (a plain path or a file: address) that cannot be OPENED fails at once with the error it had before the network rule (a
194    TransferError, resumable, "the download of ... was interrupted after 0 of N bytes (FileNotFoundError: ...)"), not after the rule's 5 minutes
195    of retries; a read that fails after the open is still resumed in the same run (a USB or network drive that hiccups mid-copy)."""
196
197    def gone(self, location):
198        t0 = time.monotonic()
199        with self.assertRaises(transfer.TransferError) as cm:
200            self.fetch(location)
201        self.assertLess(time.monotonic() - t0, 1.0)
202        self.assertIs(type(cm.exception), transfer.TransferError, "a plain TransferError, as before: not an Interrupted that is retried")
203        self.assertTrue(cm.exception.resumable)
204        self.assertTrue(str(cm.exception).startswith(f"the download of {location} was interrupted after 0 of {len(BODY)} bytes ("), str(cm.exception))
205        self.assertTrue(str(cm.exception).endswith("); the partial file is kept and the next try resumes it"), str(cm.exception))
206        self.assertFalse((self.dir / "f.part").exists(), "nothing written")
207        return str(cm.exception)
208
209    def test_a_missing_file_address_fails_at_once(self):
210        said = self.gone((self.dir / "no-such-file.pack").as_uri())
211        self.assertIn("(FileNotFoundError: ", said)
212
213    def test_a_missing_plain_path_fails_at_once(self):
214        said = self.gone(str(self.dir / "no-such-folder" / "file.pack"))
215        self.assertIn("(FileNotFoundError: ", said)
216
217    def test_a_folder_given_as_the_file_fails_at_once(self):
218        (self.dir / "a-folder").mkdir()
219        self.gone(str(self.dir / "a-folder"))               # IsADirectoryError (Linux, macOS) or PermissionError (Windows)
220
221    def test_a_read_that_fails_after_the_open_is_resumed_in_the_same_run(self):
222        source = self.dir / "source.bin"
223        source.write_bytes(BODY)
224        real_copy = transfer._copy
225        calls = []
226
227        class Hiccup:                                       # the first copy's source breaks after 3000 bytes, once
228            def __init__(self, f):
229                self.f, self.n = f, 0
230
231            def read1(self, k):
232                if self.n >= 3000:
233                    raise OSError(5, "Input/output error")
234                piece = self.f.read(min(k, 3000 - self.n))
235                self.n += len(piece)
236                return piece
237
238        def copy(src, partial, mode, done, size, progress, cancel):
239            calls.append((mode, done))
240            return real_copy(Hiccup(src) if len(calls) == 1 else src, partial, mode, done, size, progress, cancel)
241
242        with mock.patch.object(transfer, "_copy", copy):
243            self.assertEqual(self.fetch(str(source)).read_bytes(), BODY)
244        self.assertEqual(calls, [("wb", 0), ("ab", 3000)], "one more copy, from the byte the first one reached: no byte twice")
245
246
247class Destination(Scaled):
248    """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
249    it had before the network rule ("... (PermissionError: ...)" / "(OSError: [Errno 28] No space left on device)"), not retried for 5 minutes;
250    what was written stays, so freeing the space and fetching again resumes it."""
251
252    def fast_failure(self, url, end="); the partial file is kept and the next try resumes it", **kw):
253        t0 = time.monotonic()
254        with self.assertRaises(transfer.TransferError) as cm:
255            self.fetch(url, **kw)
256        self.assertLess(time.monotonic() - t0, 1.0)
257        self.assertIs(type(cm.exception), transfer.TransferError, "a plain TransferError, as before: not an Interrupted that is retried")
258        self.assertTrue(cm.exception.resumable)
259        self.assertTrue(str(cm.exception).endswith(end), str(cm.exception))
260        return str(cm.exception)
261
262    def test_a_part_file_that_may_not_be_opened_fails_at_once(self):
263        source = self.dir / "source.bin"
264        source.write_bytes(BODY)
265        real_open = Path.open
266
267        def no_part(path, *a, **k):
268            if path.name == "f.part":
269                raise PermissionError(13, "Permission denied", str(path))
270            return real_open(path, *a, **k)
271
272        with mock.patch.object(Path, "open", no_part):
273            said = self.fast_failure(str(source))
274        self.assertIn("after 0 of 10240 bytes (PermissionError: [Errno 13] Permission denied: ", said)
275        self.assertFalse((self.dir / "f.part").exists())
276
277    @unittest.skipUnless(os.name == "posix" and hasattr(os, "geteuid") and os.geteuid() != 0, "a folder without write permission: POSIX, not root")
278    def test_a_folder_without_write_permission_fails_at_once(self):
279        source = self.dir / "source.bin"
280        source.write_bytes(BODY)
281        locked = self.dir / "locked"
282        locked.mkdir()
283        locked.chmod(0o500)
284        self.addCleanup(locked.chmod, 0o700)
285        t0 = time.monotonic()
286        with self.assertRaises(transfer.TransferError) as cm:
287            transfer.download(str(source), locked / "f.part", size=len(BODY), sha256=SHA)
288        self.assertLess(time.monotonic() - t0, 1.0)
289        self.assertIs(type(cm.exception), transfer.TransferError)
290        self.assertIn("(PermissionError: [Errno 13] Permission denied: ", str(cm.exception))
291        self.assertFalse((locked / "f.part").exists())
292
293    def test_a_full_disk_fails_at_once_keeps_what_was_written_and_resumes_once_there_is_room(self):
294        behave, st = ranged(chunk=2000, every=0.01)
295        srv = Server(behave)
296        self.addCleanup(srv.close)
297        real_open = Path.open
298
299        class Full:                                        # the disk takes the first write, then: no space left
300            def __init__(self, f):
301                self.f, self.n = f, 0
302
303            def write(self, data):
304                if self.n:
305                    raise OSError(28, "No space left on device")
306                self.n += len(data)
307                return self.f.write(data)
308
309            def flush(self):
310                self.f.flush()
311
312            def __enter__(self):
313                return self
314
315            def __exit__(self, *exc):
316                self.f.close()
317
318        def full_part(path, *a, **k):
319            f = real_open(path, *a, **k)
320            return Full(f) if path.name == "f.part" else f
321
322        with mock.patch.object(Path, "open", full_part):
323            said = self.fast_failure(srv.url("/e"), end="(OSError: [Errno 28] No space left on device)", what="the engine 0.1.59 (cuda)")
324        kept = (self.dir / "f.part").read_bytes()
325        self.assertTrue(0 < len(kept) < len(BODY), len(kept))
326        self.assertEqual(kept, BODY[:len(kept)], "what was written is kept")
327        self.assertTrue(said.startswith(f"The drive that holds {self.dir} is full, so the engine 0.1.59 (cuda) stopped downloading after 1 MB of "
328                                        "1 MB. It needs about 1 MB more there ("), said)
329        self.assertIn(" is free now). Free up space on that drive, then try again; the part already downloaded is kept and the next try "
330                      "continues from there.\n(OSError: [Errno 28] No space left on device)", said)
331        self.assertEqual(self.fetch(srv.url("/e")).read_bytes(), BODY)       # room again: the next try resumes
332        self.assertEqual(st["ranges"][-1], f"bytes={len(kept)}-")
333
334    def failing_write(self, err):
335        """Path.open for f.part that takes the first write and then raises OSError(err)."""
336        real_open = Path.open
337
338        class Fails:
339            def __init__(self, f):
340                self.f, self.n = f, 0
341
342            def write(self, data):
343                if self.n:
344                    raise OSError(err, os.strerror(err))
345                self.n += len(data)
346                return self.f.write(data)
347
348            def flush(self):
349                self.f.flush()
350
351            def __enter__(self):
352                return self
353
354            def __exit__(self, *exc):
355                self.f.close()
356
357        return lambda path, *a, **k: Fails(real_open(path, *a, **k)) if path.name == "f.part" else real_open(path, *a, **k)
358
359    @unittest.skipUnless(hasattr(errno, "EDQUOT"), "no EDQUOT here")
360    def test_a_used_up_quota_fails_at_once_in_plain_words(self):
361        srv = Server(ranged(chunk=2000, every=0.01)[0])
362        self.addCleanup(srv.close)
363        with mock.patch.object(Path, "open", self.failing_write(errno.EDQUOT)):
364            said = self.fast_failure(srv.url("/e"), end=f"(OSError: [Errno {errno.EDQUOT}] {os.strerror(errno.EDQUOT)})",
365                                     what="the picture reader")
366        self.assertTrue(said.startswith(f"Your storage quota on the drive that holds {self.dir} is used up, so the picture reader stopped "
367                                        "downloading after 1 MB of 1 MB. It needs about 1 MB more there. Delete files you no longer need, or ask "
368                                        "whoever looks after this computer for a larger quota, then try again; the part already downloaded is kept "
369                                        "and the next try continues from there.\n("), said)
370        self.assertGreater((self.dir / "f.part").stat().st_size, 0)
371
372    def test_a_read_only_drive_fails_at_once_in_plain_words_also_at_the_open(self):
373        srv = Server(ranged()[0])
374        self.addCleanup(srv.close)
375        real_open = Path.open
376
377        def ro(path, *a, **k):
378            if path.name == "f.part":
379                raise OSError(errno.EROFS, "Read-only file system")
380            return real_open(path, *a, **k)
381
382        with mock.patch.object(Path, "open", ro):           # before: an OSError at the open was an Interrupted, retried for 5 minutes
383            said = self.fast_failure(srv.url("/e"), end=f"(OSError: [Errno {errno.EROFS}] Read-only file system)")
384        self.assertTrue(said.startswith(f"The drive that holds {self.dir} can only be read right now, not written, so the file e could not be "
385                                        "saved there. Restart the computer and try again; if the drive stays read-only, check it for errors. "
386                                        f"Nothing was saved yet.\n(OSError: [Errno {errno.EROFS}] "), said)
387
388    def test_permission_keeps_its_words(self):
389        e = PermissionError(errno.EACCES, "Permission denied")
390        self.assertIsNone(transfer.no_room_words(e, self.dir / "f.part", 5, 10, "x"))
391        self.assertIsNone(transfer.no_room_words(OSError(errno.EIO, "I/O error"), self.dir / "f.part", 5, 10, "x"))
392        self.assertIsNone(transfer.no_room_words(ValueError("no"), self.dir / "f.part", 5, 10, "x"))
393
394
395class NoRoomWords(unittest.TestCase):
396    """The sentences themselves, with real-sized numbers (no transfer)."""
397    PART = Path("/home/ana/.local/share/strata/updates/partial/1f2e3d4c5b6a7980.part")
398
399    def words(self, err, got, size, free=None, what="the engine 0.1.59 (cuda)", **kw):
400        usage = mock.Mock(free=free) if free is not None else None
401        with mock.patch.object(transfer.shutil, "disk_usage", return_value=usage, side_effect=None if usage else OSError("gone")) as du:
402            said = transfer.no_room_words(OSError(err, os.strerror(err)), self.PART, got, size, what, **kw)
403        if err == errno.ENOSPC:
404            du.assert_called_once_with(str(self.PART.parent))
405        return said
406
407    def test_full(self):
408        self.assertEqual(self.words(errno.ENOSPC, 412_300_000, 1_930_000_000, free=0),
409                         f"The drive that holds {self.PART.parent} is full, so the engine 0.1.59 (cuda) stopped downloading after 412 MB of 1.9 GB. "
410                         "It needs about 1.5 GB more there (0 MB is free now). Free up space on that drive, then try again; the part already "
411                         f"downloaded is kept and the next try continues from there.\n(OSError: [Errno {errno.ENOSPC}] {os.strerror(errno.ENOSPC)})")
412
413    def test_full_free_space_unreadable_and_nothing_written_yet(self):
414        said = self.words(errno.ENOSPC, 0, 22_850_000_000)
415        self.assertIn("after 0 MB of 22.9 GB. It needs about 22.9 GB more there. Free up space on that drive, then try again; nothing was "
416                      "saved yet.\n(OSError:", said)
417
418    def test_windows_disk_full_codes(self):
419        for code in (112, 39):
420            e = OSError(errno.ENOSPC, "There is not enough space on the disk")
421            e.winerror = code
422            self.assertTrue(transfer.no_room_words(e, self.PART, 1, 2, "x").startswith("The drive that holds"))
423
424    @unittest.skipUnless(hasattr(errno, "EDQUOT"), "no EDQUOT here")
425    def test_quota(self):
426        said = self.words(errno.EDQUOT, 3_000_000_000, 5_200_000_000)
427        self.assertTrue(said.startswith(f"Your storage quota on the drive that holds {self.PART.parent} is used up, so the engine 0.1.59 (cuda) "
428                                        "stopped downloading after 3.0 GB of 5.2 GB. It needs about 2.2 GB more there."), said)
429
430    def test_read_only_with_a_kept_part(self):
431        said = self.words(errno.EROFS, 700_000_000, 1_930_000_000)
432        self.assertIn("so the engine 0.1.59 (cuda) could not be saved there. Restart the computer and try again; if the drive stays read-only, "
433                      "check it for errors. The part already downloaded is kept and the next try continues from there.\n(OSError:", said)
434
435    def test_the_generic_name_becomes_the_file_name(self):
436        said = self.words(errno.ENOSPC, 1, 2, what="the download", location="https://example.org/a/b/strata-0.1.59-cuda.zip")
437        self.assertIn(" is full, so the file strata-0.1.59-cuda.zip stopped downloading after ", said)
438
439
440if __name__ == "__main__":
441    unittest.main()