Retry transient snapshot downloads and report progress

This commit is contained in:
Andrei Smaliak 2026-10-03 11:22:38 +02:00
parent 26f75a9314
commit 635466b94c
4 changed files with 125 additions and 7 deletions

View File

@ -17,3 +17,13 @@
control file, backup verification, safety/continuation regression tests, control file, backup verification, safety/continuation regression tests,
shell syntax and generated systemd unit validation. Hardware boot validation shell syntax and generated systemd unit validation. Hardware boot validation
on the affected Edge remains outstanding. on the affected Edge remains outstanding.
- Installer snapshot downloads now retry transient network failures up to three
times per file, with a 30-second socket timeout and three concurrent workers.
Completed verified files stay available during retries in the same run; failed
recovery snapshots are still removed if recovery has not been armed.
- Download progress, retry paths, final failures, catalog verification and the
pre-reboot filesystem sync are reported explicitly. Authentication, certificate
and checksum failures are not bypassed or retried as transient network errors.
- Download validation on g-box-7e579e52: all 148 files verified in 79.6 seconds,
including a real read timeout recovered by retry. Python 3.9 socket timeout
handling and non-retryable authentication/certificate errors tested on Edge.

View File

@ -3,11 +3,12 @@
APT method protocol: https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/ APT method protocol: https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/
""" """
import base64 import base64
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
import fcntl import fcntl
import gzip import gzip
import importlib.util import importlib.util
import hashlib import hashlib
import http.client
import json import json
import os import os
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
@ -15,9 +16,13 @@ import pwd
import re import re
import shutil import shutil
import signal import signal
import socket
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
import time
import ssl
import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
@ -99,12 +104,64 @@ def check_existing(dest):
elif dest.exists() and any(dest.iterdir()): elif dest.exists() and any(dest.iterdir()):
raise ValueError('Refusing to replace an unidentified nonempty directory') raise ValueError('Refusing to replace an unidentified nonempty directory')
def transient_download_error(error):
if isinstance(error, urllib.error.HTTPError):
return error.code in (408, 429, 500, 502, 503, 504)
if isinstance(error, urllib.error.URLError):
error = error.reason
return isinstance(error, (TimeoutError, socket.timeout, ConnectionError, http.client.IncompleteRead)) and not isinstance(error, ssl.SSLCertVerificationError)
def snapshot_bytes(repo, commit, auth, path):
for attempt in range(1, 4):
started = time.monotonic()
try:
with open_git(repo, raw_endpoint(path, commit), auth, timeout=30) as response:
return response.read()
except Exception as error:
if not transient_download_error(error):
raise
elapsed = time.monotonic() - started
print(f'Download {path}: {type(error).__name__} after {elapsed:.1f}s '
f'(attempt {attempt}/3)', flush=True)
if attempt == 3:
raise RuntimeError(f'Git download failed after 3 attempts: {path} '
f'({type(error).__name__})') from error
time.sleep(attempt * 2)
def download_snapshot(files, download):
started = time.monotonic()
completed = 0
print(f'Downloading {len(files)} files, 3 workers; network timeout 30s, up to 3 attempts per file', flush=True)
with ThreadPoolExecutor(max_workers=3) as pool:
pending = {pool.submit(download, item): item['path'] for item in files}
try:
while pending:
done, _ = wait(pending, timeout=10, return_when=FIRST_COMPLETED)
if not done:
print(f'Download progress: {completed}/{len(files)}, '
f'{time.monotonic() - started:.0f}s elapsed; waiting for HTTPS', flush=True)
for future in done:
path = pending.pop(future)
try:
future.result()
except Exception:
print('Download failed: ' + path, flush=True)
raise
completed += 1
print(f'Download progress: {completed}/{len(files)} verified: {path}', flush=True)
finally:
for future in pending:
future.cancel()
print(f'Download complete: {completed} files in {time.monotonic() - started:.1f}s', flush=True)
def materialize_file(repo, commit, auth, entry, existing, staged): def materialize_file(repo, commit, auth, entry, existing, staged):
old = existing / entry['path'] old = existing / entry['path']
data = old.read_bytes() if old.is_file() and not old.is_symlink() else None data = old.read_bytes() if old.is_file() and not old.is_symlink() else None
if data is None or blob_hash(data) != entry['sha']: if data is None or blob_hash(data) != entry['sha']:
with open_git(repo, raw_endpoint(entry['path'], commit), auth) as response: data = snapshot_bytes(repo, commit, auth, entry['path'])
data = response.read()
if blob_hash(data) != entry['sha']: if blob_hash(data) != entry['sha']:
raise ValueError('Git blob checksum mismatch: ' + entry['path']) raise ValueError('Git blob checksum mismatch: ' + entry['path'])
p = staged / entry['path'] p = staged / entry['path']
@ -144,12 +201,13 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
if shutil.disk_usage(root).free < recovery.RESERVE: if shutil.disk_usage(root).free < recovery.RESERVE:
raise RuntimeError('Not enough system disk space for recovery installer') raise RuntimeError('Not enough system disk space for recovery installer')
materialize_file(repo, commit, auth, item, root / 'absent', root) materialize_file(repo, commit, auth, item, root / 'absent', root)
with ThreadPoolExecutor(max_workers=6) as pool: download_snapshot(files, download)
list(pool.map(download, files))
write_json(root / '.iomatex-source.json', write_json(root / '.iomatex-source.json',
{'repo': repo, 'branch': branch, 'commit': commit, 'files': files}) {'repo': repo, 'branch': branch, 'commit': commit, 'files': files})
print('Verifying recovery package catalog...', flush=True)
catalog(root) catalog(root)
write_json(AUTH, auth, 0o600) write_json(AUTH, auth, 0o600)
print('Preparing offline recovery...', flush=True)
recovery.arm(root, stages, report, job) recovery.arm(root, stages, report, job)
except Exception: except Exception:
# Keep evidence and snapshots once a boot recovery request exists. # Keep evidence and snapshots once a boot recovery request exists.
@ -198,8 +256,7 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
def download(entry): def download(entry):
materialize_file(repo, commit, auth, entry, dest, staged) materialize_file(repo, commit, auth, entry, dest, staged)
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True) print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
with ThreadPoolExecutor(max_workers=6) as pool: download_snapshot(files, download)
list(pool.map(download, files))
source = {'repo': repo, 'commit': commit, 'branch': branch, 'files': files} source = {'repo': repo, 'commit': commit, 'branch': branch, 'files': files}
write_json(staged / '.iomatex-source.json', source) write_json(staged / '.iomatex-source.json', source)
# Validate all metadata before replacing an existing installation snapshot. # Validate all metadata before replacing an existing installation snapshot.

View File

@ -36,6 +36,56 @@ class DeliveryTest(unittest.TestCase):
with self.assertRaises(ValueError): d.download_object(config,'debian/test.deb',target,{}) with self.assertRaises(ValueError): d.download_object(config,'debian/test.deb',target,{})
self.assertFalse(target.exists()) self.assertFalse(target.exists())
def test_read_timeout_retries_only_failed_file_and_verifies_result(self):
class Stalled(io.BytesIO):
def read(self, *args):
raise d.socket.timeout('read timed out')
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
data = b'verified content'
entry = {'path': 'a.sh', 'mode': '100755', 'sha': d.blob_hash(data)}
with patch.object(d, 'open_git', side_effect=[Stalled(), io.BytesIO(data)]) as opened, patch.object(d.time, 'sleep'):
d.materialize_file('An-J/Iomatex_OS', 'a'*40, {}, entry, root/'absent', root)
self.assertEqual(opened.call_count, 2)
self.assertEqual((root/'a.sh').read_bytes(), data)
def test_snapshot_retries_do_not_redownload_successful_files(self):
calls = {'good': 0, 'flaky': 0}
def open_file(repo, endpoint, auth, timeout):
path = endpoint.split('/')[1].split('?')[0]
calls[path] += 1
if path == 'flaky' and calls[path] == 1:
raise d.socket.timeout('temporary')
return io.BytesIO(path.encode())
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
entries = [{'path': path, 'mode': '100644', 'sha': d.blob_hash(path.encode())} for path in calls]
with patch.object(d, 'open_git', side_effect=open_file), patch.object(d.time, 'sleep'):
d.download_snapshot(entries, lambda e: d.materialize_file('An-J/Iomatex_OS', 'a'*40, {}, e, root/'absent', root))
self.assertEqual(calls, {'good': 1, 'flaky': 2})
self.assertEqual((root/'good').read_bytes(), b'good')
self.assertEqual((root/'flaky').read_bytes(), b'flaky')
def test_retry_exhaustion_has_path_and_no_partial_file(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
entry = {'path': 'a.sh', 'mode': '100644', 'sha': d.blob_hash(b'ok')}
with patch.object(d, 'open_git', side_effect=TimeoutError()) as opened, patch.object(d.time, 'sleep'):
with self.assertRaisesRegex(RuntimeError, '3 attempts: a.sh'):
d.materialize_file('An-J/Iomatex_OS', 'a'*40, {}, entry, root/'absent', root)
self.assertEqual(opened.call_count, 3)
self.assertFalse((root/'a.sh').exists())
def test_authentication_and_certificate_failures_are_not_retried(self):
errors = [d.urllib.error.HTTPError('https://example', 401, 'Unauthorized', {}, None),
d.urllib.error.URLError(d.ssl.SSLCertVerificationError('certificate'))]
for error in errors:
with self.subTest(error=type(error).__name__), patch.object(d, 'open_git', side_effect=error) as opened:
with self.assertRaises(type(error)):
d.snapshot_bytes('An-J/Iomatex_OS', 'a'*40, {}, 'a.sh')
self.assertEqual(opened.call_count, 1)
self.assertTrue(d.transient_download_error(d.urllib.error.HTTPError('https://example', 503, 'Busy', {}, None)))
def test_catalog_includes_node_and_vendor_plugin(self): def test_catalog_includes_node_and_vendor_plugin(self):
text, objects=d.catalog(Path(__file__).resolve().parents[1]) text, objects=d.catalog(Path(__file__).resolve().parents[1])
self.assertIn('Package: nodejs\n',text) self.assertIn('Package: nodejs\n',text)

View File

@ -200,6 +200,7 @@ def arm(root, stages, report, job=None):
artifacts=tempfile.mkdtemp(prefix='attempt-', dir=BASE), created_at=int(time.time()))) artifacts=tempfile.mkdtemp(prefix='attempt-', dir=BASE), created_at=int(time.time())))
output(['systemctl', 'daemon-reload']) output(['systemctl', 'daemon-reload'])
output(['systemctl', 'enable', PREPARE, RESUME]) output(['systemctl', 'enable', PREPARE, RESUME])
print('Syncing filesystems before recovery reboot...', flush=True)
os.sync() os.sync()
print('Userdata recovery queued. Update will resume after offline verification.', flush=True) print('Userdata recovery queued. Update will resume after offline verification.', flush=True)
output(['systemctl', 'reboot']) output(['systemctl', 'reboot'])