Coverage for tools/archive_import_helper.py: 95%

403 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2026-11-21 08:51 +0000

1#! /usr/bin/python3 

2# SPDX-License-Identifier: GPL-2.0-or-later 

3# © 2026, Ansgar 🙀 <ansgar@debian.org> 

4 

5""" 

6Fill the pool of a suite imported into archive.debian.org 

7 

8Read ``dists/<suite>/Release`` and the ``Packages.xz`` and ``Sources.xz`` 

9indices it lists, determine which pool files are missing below the 

10archive root and download them from a single base URL. Existing files 

11are skipped (with a warning if their size does not match the index); 

12downloaded files are verified against size and SHA256 from the index 

13and get the mtime reported by the server. 

14 

15Workflow for bullseye-security, whose pool is no longer on the security 

16mirrors: 

17 

18 1. archive_import_helper.py --source https://deb.debian.org/debian/ \\ 

19 --rewrite-path pool/updates/=pool/ ROOT bullseye-security 

20 fetches everything that also exists in the main archive; 

21 2. archive_import_helper.py --delay 1 \\ 

22 --source https://snapshot.debian.org/archive/debian-security/20260901T000000Z/ \\ 

23 ROOT bullseye-security 

24 fetches the remainder from snapshot.debian.org. 

25 

26Paths of files still missing after a run are printed to stdout, one per 

27line; everything else goes to stderr. 

28""" 

29 

30import argparse 

31import contextlib 

32import email.utils 

33import enum 

34import hashlib 

35import http.client 

36import logging 

37import os 

38import re 

39import ssl 

40import stat 

41import sys 

42import time 

43import urllib.error 

44import urllib.parse 

45import urllib.request 

46from collections.abc import Callable, Iterable, Iterator, Mapping 

47from dataclasses import dataclass, field 

48from typing import TextIO 

49 

50import apt_pkg 

51 

52INDEX_SUFFIXES = ("/Packages.xz", "/Sources.xz") 

53CHUNK_SIZE = 1 << 20 

54PART_SUFFIX = ".part" 

55 

56BACKOFF_BASE = 1.0 # seconds; doubled on every retry 

57BACKOFF_BASE_RATELIMIT = 5.0 # for HTTP 429/503 without Retry-After 

58BACKOFF_MAX = 120.0 

59RETRY_AFTER_MAX = 900.0 # cap for server-supplied Retry-After 

60MAX_CONSECUTIVE_FAILURES = 10 # abort: the source is probably down 

61USER_AGENT = "archive-import-helper/1 (archive.debian.org import; ftpmaster@debian.org)" 

62 

63NOT_FOUND_STATUS = frozenset({404, 410}) 

64RATE_LIMIT_STATUS = frozenset({429, 503}) 

65TRANSIENT_STATUS = frozenset({408, 500, 502, 504}) 

66TRANSIENT_ERRORS = ( 

67 urllib.error.URLError, 

68 http.client.HTTPException, 

69 ConnectionError, 

70 TimeoutError, 

71 ssl.SSLError, 

72) 

73 

74# same character set as daklib.regexes.re_file_safe(_slash) 

75RE_SAFE_PATH = re.compile(r"\A[a-zA-Z0-9][/a-zA-Z0-9_.~+-]*\Z") 

76RE_SAFE_NAME = re.compile(r"\A[a-zA-Z0-9][a-zA-Z0-9_.~+-]*\Z") 

77RE_SHA256 = re.compile(r"\A[0-9a-f]{64}\Z") 

78 

79log = logging.getLogger("archive-import-helper") 

80 

81 

82class ArchiveError(Exception): 

83 """fatal problem: inconsistent indices, unsafe paths, unusable arguments""" 

84 

85 

86@dataclass(frozen=True, slots=True) 

87class FileInfo: 

88 """a file with its expected size and SHA256 

89 

90 `path` is either a pool path as listed in `Filename:` or an index 

91 path relative to `dists/<suite>/`. 

92 """ 

93 

94 path: str 

95 size: int 

96 sha256: str 

97 

98 

99@dataclass(frozen=True, slots=True) 

100class Release: 

101 suite: str 

102 codename: str 

103 date: str 

104 files: dict[str, FileInfo] 

105 

106 

107def parse_size(value: str, context: str) -> int: 

108 try: 

109 size = int(value) 

110 except ValueError: 

111 size = -1 

112 if size < 0: 

113 raise ArchiveError(f"{context}: invalid size {value!r}") 

114 return size 

115 

116 

117def parse_sha256(value: str, context: str) -> str: 

118 sha256 = value.lower() 

119 if not RE_SHA256.match(sha256): 

120 raise ArchiveError(f"{context}: invalid SHA256 {value!r}") 

121 return sha256 

122 

123 

124def parse_checksum_lines(value: str, context: str) -> Iterator[tuple[str, int, str]]: 

125 """parse `<sha256> <size> <name>` lines (Release, Checksums-Sha256)""" 

126 for line in value.splitlines(): 

127 parts = line.split() 

128 if not parts: 128 ↛ 129line 128 didn't jump to line 129 because the condition on line 128 was never true

129 continue 

130 if len(parts) != 3: 

131 raise ArchiveError(f"{context}: malformed checksum line {line!r}") 

132 sha256, size, name = parts 

133 yield parse_sha256(sha256, context), parse_size(size, context), name 

134 

135 

136def require_field(section: apt_pkg.TagSection, field: str, context: str) -> str: 

137 try: 

138 return section[field] 

139 except KeyError: 

140 raise ArchiveError(f"{context}: missing {field} field") 

141 

142 

143def read_release(path: str) -> Release: 

144 """parse a plain (unsigned) Release file""" 

145 with open(path, "rb") as fh: 

146 section = apt_pkg.TagSection(fh.read()) 

147 files = { 

148 name: FileInfo(name, size, sha256) 

149 for sha256, size, name in parse_checksum_lines( 

150 require_field(section, "SHA256", path), path 

151 ) 

152 } 

153 return Release( 

154 suite=section.get("Suite", ""), 

155 codename=section.get("Codename", ""), 

156 date=section.get("Date", ""), 

157 files=files, 

158 ) 

159 

160 

161def select_indices(release: Release) -> list[FileInfo]: 

162 """the Packages.xz and Sources.xz indices listed in `release`""" 

163 return sorted( 

164 (info for info in release.files.values() if info.path.endswith(INDEX_SUFFIXES)), 

165 key=lambda info: info.path, 

166 ) 

167 

168 

169def sha256_file(path: str) -> str: 

170 with open(path, "rb") as fh: 

171 return hashlib.file_digest(fh, "sha256").hexdigest() 

172 

173 

174def verify_file(path: str, expected: FileInfo) -> None: 

175 """raise `ArchiveError` unless `path` exists with the expected size and SHA256""" 

176 try: 

177 size = os.stat(path).st_size 

178 except FileNotFoundError: 

179 raise ArchiveError(f"{path}: missing, but listed in Release") from None 

180 if size != expected.size: 

181 raise ArchiveError( 

182 f"{path}: size {size} does not match Release ({expected.size})" 

183 ) 

184 sha256 = sha256_file(path) 

185 if sha256 != expected.sha256: 

186 raise ArchiveError( 

187 f"{path}: SHA256 {sha256} does not match Release ({expected.sha256})" 

188 ) 

189 

190 

191def check_pool_path(path: str) -> None: 

192 """raise `ArchiveError` unless `path` is a safe relative path below pool/""" 

193 if not RE_SAFE_PATH.match(path): 

194 raise ArchiveError(f"unsafe pool path {path!r}") 

195 components = path.split("/") 

196 if any(component in ("", ".", "..") for component in components): 

197 raise ArchiveError(f"unsafe pool path {path!r}") 

198 if len(components) < 2 or components[0] != "pool": 

199 raise ArchiveError(f"path not below pool/: {path!r}") 

200 

201 

202def read_packages(path: str) -> Iterator[FileInfo]: 

203 """yield the pool files listed in a (possibly compressed) Packages index""" 

204 with apt_pkg.TagFile(path) as tagfile: 

205 for section in tagfile: 

206 context = f"{path}: {section.get('Package', '<unknown>')}" 

207 filename = require_field(section, "Filename", context) 

208 size = parse_size(require_field(section, "Size", context), context) 

209 sha256 = parse_sha256(require_field(section, "SHA256", context), context) 

210 yield FileInfo(filename, size, sha256) 

211 

212 

213def read_sources(path: str) -> Iterator[FileInfo]: 

214 """yield the pool files listed in a (possibly compressed) Sources index""" 

215 with apt_pkg.TagFile(path) as tagfile: 

216 for section in tagfile: 

217 context = f"{path}: {section.get('Package', '<unknown>')}" 

218 directory = require_field(section, "Directory", context) 

219 checksums = require_field(section, "Checksums-Sha256", context) 

220 for sha256, size, name in parse_checksum_lines(checksums, context): 

221 if not RE_SAFE_NAME.match(name): 

222 raise ArchiveError(f"{context}: unsafe file name {name!r}") 

223 yield FileInfo(f"{directory}/{name}", size, sha256) 

224 

225 

226def read_index(path: str) -> Iterator[FileInfo]: 

227 name = os.path.basename(path) 

228 if name.startswith("Packages"): 

229 return read_packages(path) 

230 if name.startswith("Sources"): 

231 return read_sources(path) 

232 raise ArchiveError(f"{path}: not a Packages or Sources index") 

233 

234 

235def collect_pool_files( 

236 entries: Iterable[FileInfo], 

237) -> tuple[dict[str, FileInfo], list[str]]: 

238 """map pool paths to `FileInfo`, dropping duplicates 

239 

240 Identical duplicates (arch:all packages are listed in every 

241 binary-<arch> index) are silently merged. Entries that disagree on 

242 size or SHA256 keep the first one seen and are returned as the 

243 second element, one path each, after logging a warning. 

244 """ 

245 files: dict[str, FileInfo] = {} 

246 conflicts: set[str] = set() 

247 for info in entries: 

248 check_pool_path(info.path) 

249 first = files.setdefault(info.path, info) 

250 if first != info and info.path not in conflicts: 

251 conflicts.add(info.path) 

252 log.warning( 

253 "%s: conflicting index entries (size %d, SHA256 %s vs. size %d," 

254 " SHA256 %s); keeping the first", 

255 info.path, 

256 first.size, 

257 first.sha256, 

258 info.size, 

259 info.sha256, 

260 ) 

261 return files, list(conflicts) 

262 

263 

264def check_existing( 

265 root: str, files: Mapping[str, FileInfo] 

266) -> tuple[list[FileInfo], list[str]]: 

267 """split `files` into missing and present ones 

268 

269 Returns the missing files sorted by path, and the paths of files 

270 that exist but are not regular files of the expected size. The 

271 latter are only reported with a warning, never replaced. 

272 """ 

273 missing: list[FileInfo] = [] 

274 size_mismatches: list[str] = [] 

275 for path in sorted(files): 

276 info = files[path] 

277 try: 

278 st = os.stat(os.path.join(root, path)) 

279 except FileNotFoundError: 

280 missing.append(info) 

281 continue 

282 if not stat.S_ISREG(st.st_mode): 

283 log.warning("%s: exists, but is not a regular file", path) 

284 size_mismatches.append(path) 

285 elif st.st_size != info.size: 

286 log.warning( 

287 "%s: size %d does not match index (%d)", path, st.st_size, info.size 

288 ) 

289 size_mismatches.append(path) 

290 else: 

291 log.debug("%s: present", path) 

292 return missing, size_mismatches 

293 

294 

295def parse_rewrite(value: str) -> tuple[str, str]: 

296 """parse an `OLD=NEW` prefix rewrite rule (argparse type)""" 

297 old, sep, new = value.partition("=") 

298 if not sep or not old: 

299 raise argparse.ArgumentTypeError( 

300 f"expected OLD=NEW with a non-empty OLD, got {value!r}" 

301 ) 

302 return old, new 

303 

304 

305def rewrite_path(path: str, rule: tuple[str, str] | None) -> str: 

306 """replace the prefix `rule[0]` of `path` by `rule[1]` if it matches""" 

307 if rule is None or not path.startswith(rule[0]): 

308 return path 

309 old, new = rule 

310 return new + path[len(old) :] 

311 

312 

313def build_url(base: str, remote_path: str) -> str: 

314 return base.rstrip("/") + "/" + urllib.parse.quote(remote_path) 

315 

316 

317def parse_retry_after(value: str | None, now: float) -> float | None: 

318 """seconds to wait according to a Retry-After header, None if unusable""" 

319 if value is None: 

320 return None 

321 value = value.strip() 

322 if value.isdigit(): 

323 return float(value) 

324 try: 

325 when = email.utils.parsedate_to_datetime(value) 

326 except (TypeError, ValueError): 

327 return None 

328 return max(0.0, when.timestamp() - now) 

329 

330 

331class TruncatedResponse(http.client.HTTPException): 

332 """the connection was closed before Content-Length bytes arrived""" 

333 

334 

335class Outcome(enum.Enum): 

336 FETCHED = "fetched" 

337 NOT_FOUND = "not found" 

338 MISMATCH = "mismatch" 

339 FAILED = "failed" 

340 

341 

342@dataclass(frozen=True, slots=True) 

343class FetchResult: 

344 outcome: Outcome 

345 detail: str = "" 

346 mtime_set: bool = False 

347 

348 

349def set_mtime(path: str, last_modified: str | None) -> bool: 

350 """set the mtime of `path` from a Last-Modified header; False if unusable""" 

351 if last_modified is None: 

352 return False 

353 try: 

354 when = email.utils.parsedate_to_datetime(last_modified) 

355 except (TypeError, ValueError): 

356 return False 

357 timestamp = when.timestamp() 

358 os.utime(path, (timestamp, timestamp)) 

359 return True 

360 

361 

362class Downloader: 

363 """download files with retries, verification and mtime handling 

364 

365 `sleep` and `now` can be replaced by tests. 

366 """ 

367 

368 def __init__( 

369 self, 

370 *, 

371 timeout: float = 60.0, 

372 max_retries: int = 5, 

373 delay: float = 0.0, 

374 sleep: Callable[[float], None] = time.sleep, 

375 now: Callable[[], float] = time.time, 

376 ) -> None: 

377 self.timeout = timeout 

378 self.max_retries = max_retries 

379 self.delay = delay 

380 self._sleep = sleep 

381 self._now = now 

382 self._first = True 

383 

384 def fetch(self, url: str, dest: str, expected: FileInfo) -> FetchResult: 

385 """download `url` to `dest` if it matches `expected` 

386 

387 The data is written to `dest + PART_SUFFIX` and only renamed to 

388 `dest` after size and SHA256 have been verified, so `dest` is 

389 either absent or complete. HTTP 404/410 give `NOT_FOUND`, a 

390 file that does not match the index `MISMATCH`; rate limits and 

391 transient errors are retried up to `max_retries` times before 

392 giving up with `FAILED`. 

393 """ 

394 if not self._first and self.delay > 0: 

395 self._sleep(self.delay) 

396 self._first = False 

397 os.makedirs(os.path.dirname(dest), exist_ok=True) 

398 tmp = dest + PART_SUFFIX 

399 error = "" 

400 for attempt in range(self.max_retries + 1): 

401 try: 

402 with self._open(url) as response: 

403 return self._download(response, tmp, dest, expected) 

404 except urllib.error.HTTPError as e: 

405 if e.code in NOT_FOUND_STATUS: 

406 return FetchResult(Outcome.NOT_FOUND, f"HTTP {e.code}") 

407 error = f"HTTP {e.code}" 

408 if e.code in RATE_LIMIT_STATUS: 

409 self._backoff( 

410 attempt, 

411 error, 

412 retry_after=e.headers.get("Retry-After"), 

413 rate_limited=True, 

414 ) 

415 elif e.code in TRANSIENT_STATUS: 

416 self._backoff(attempt, error) 

417 else: 

418 return FetchResult(Outcome.FAILED, error) 

419 except TRANSIENT_ERRORS as e: 

420 error = f"{type(e).__name__}: {e}" 

421 self._backoff(attempt, error) 

422 return FetchResult( 

423 Outcome.FAILED, f"giving up after {self.max_retries} retries: {error}" 

424 ) 

425 

426 def _open(self, url: str) -> http.client.HTTPResponse: 

427 request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) 

428 response: http.client.HTTPResponse = urllib.request.urlopen( 

429 request, timeout=self.timeout 

430 ) 

431 return response 

432 

433 def _backoff( 

434 self, 

435 attempt: int, 

436 why: str, 

437 *, 

438 retry_after: str | None = None, 

439 rate_limited: bool = False, 

440 ) -> None: 

441 """sleep before the next attempt; no-op after the last one""" 

442 if attempt >= self.max_retries: 

443 return 

444 wait = parse_retry_after(retry_after, self._now()) 

445 if wait is not None: 

446 wait = min(wait, RETRY_AFTER_MAX) 

447 else: 

448 base = BACKOFF_BASE_RATELIMIT if rate_limited else BACKOFF_BASE 

449 wait = min(base * 2**attempt, BACKOFF_MAX) 

450 log.info( 

451 "%s; retrying in %.0f s (retry %d of %d)", 

452 why, 

453 wait, 

454 attempt + 1, 

455 self.max_retries, 

456 ) 

457 self._sleep(wait) 

458 

459 def _download( 

460 self, 

461 response: http.client.HTTPResponse, 

462 tmp: str, 

463 dest: str, 

464 expected: FileInfo, 

465 ) -> FetchResult: 

466 log.debug("%s: downloading %s", expected.path, response.url) 

467 content_length = response.headers.get("Content-Length") 

468 if content_length is not None: 468 ↛ 476line 468 didn't jump to line 476 because the condition on line 468 was always true

469 content_length = content_length.strip() 

470 if content_length != str(expected.size): 

471 return FetchResult( 

472 Outcome.MISMATCH, 

473 f"Content-Length {content_length} does not match index size" 

474 f" {expected.size}", 

475 ) 

476 digest = hashlib.sha256() 

477 size = 0 

478 try: 

479 with open(tmp, "wb") as fh: 

480 while chunk := response.read(CHUNK_SIZE): 

481 digest.update(chunk) 

482 fh.write(chunk) 

483 size += len(chunk) 

484 fh.flush() 

485 os.fsync(fh.fileno()) 

486 if size != expected.size: 

487 if content_length is not None: 487 ↛ 491line 487 didn't jump to line 491 because the condition on line 487 was always true

488 # the server announced the right size, so the 

489 # connection was cut short: worth a retry 

490 raise TruncatedResponse(f"received {size} of {expected.size} bytes") 

491 os.unlink(tmp) 

492 return FetchResult( 

493 Outcome.MISMATCH, 

494 f"size {size} does not match index ({expected.size})", 

495 ) 

496 sha256 = digest.hexdigest() 

497 if sha256 != expected.sha256: 

498 os.unlink(tmp) 

499 return FetchResult( 

500 Outcome.MISMATCH, 

501 f"SHA256 {sha256} does not match index ({expected.sha256})", 

502 ) 

503 mtime_set = set_mtime(tmp, response.headers.get("Last-Modified")) 

504 os.replace(tmp, dest) 

505 except BaseException: 

506 with contextlib.suppress(FileNotFoundError): 

507 os.unlink(tmp) 

508 raise 

509 return FetchResult( 

510 Outcome.FETCHED, "" if mtime_set else "no Last-Modified", mtime_set 

511 ) 

512 

513 

514@dataclass 

515class Report: 

516 """what happened to the pool files of a suite""" 

517 

518 listed: int = 0 

519 present: int = 0 

520 fetched: int = 0 

521 no_mtime: int = 0 

522 size_mismatch: list[str] = field(default_factory=list) 

523 conflicts: list[str] = field(default_factory=list) 

524 not_found: list[str] = field(default_factory=list) 

525 mismatched: list[tuple[str, str]] = field(default_factory=list) 

526 failed: list[tuple[str, str]] = field(default_factory=list) 

527 not_attempted: list[str] = field(default_factory=list) 

528 

529 def record(self, info: FileInfo, result: FetchResult) -> None: 

530 match result.outcome: 

531 case Outcome.FETCHED: 

532 self.fetched += 1 

533 if not result.mtime_set: 533 ↛ 534line 533 didn't jump to line 534 because the condition on line 533 was never true

534 self.no_mtime += 1 

535 note = f"; {result.detail}" if result.detail else "" 

536 log.info("fetched %s (%d bytes)%s", info.path, info.size, note) 

537 case Outcome.NOT_FOUND: 

538 self.not_found.append(info.path) 

539 log.info("not found at source: %s (%s)", info.path, result.detail) 

540 case Outcome.MISMATCH: 540 ↛ 541line 540 didn't jump to line 541 because the pattern on line 540 never matched

541 self.mismatched.append((info.path, result.detail)) 

542 log.warning("mismatch: %s: %s", info.path, result.detail) 

543 case Outcome.FAILED: 543 ↛ exitline 543 didn't return from function 'record' because the pattern on line 543 always matched

544 self.failed.append((info.path, result.detail)) 

545 log.warning("failed: %s: %s", info.path, result.detail) 

546 

547 def still_missing(self) -> list[str]: 

548 return sorted( 

549 self.not_found 

550 + [path for path, _ in self.mismatched] 

551 + [path for path, _ in self.failed] 

552 + self.not_attempted 

553 ) 

554 

555 def has_problems(self) -> bool: 

556 return bool( 

557 self.size_mismatch or self.conflicts or self.mismatched or self.failed 

558 ) 

559 

560 def summary(self) -> str: 

561 return ( 

562 f"{self.listed} pool files listed: {self.present} present" 

563 f" ({len(self.size_mismatch)} with size mismatch)," 

564 f" {self.fetched} fetched ({self.no_mtime} without Last-Modified)," 

565 f" {len(self.not_found)} not found at source," 

566 f" {len(self.mismatched)} mismatched, {len(self.failed)} failed," 

567 f" {len(self.not_attempted)} not attempted;" 

568 f" {len(self.still_missing())} still missing" 

569 ) 

570 

571 

572def load_pool_files(root: str, suite: str) -> tuple[dict[str, FileInfo], list[str]]: 

573 """collect the pool files of `suite`, verifying the indices against Release""" 

574 dists = os.path.join(root, "dists", suite) 

575 release = read_release(os.path.join(dists, "Release")) 

576 log.info( 

577 "Release: Suite %s, Codename %s, Date %s", 

578 release.suite, 

579 release.codename, 

580 release.date, 

581 ) 

582 indices = select_indices(release) 

583 if not indices: 583 ↛ 584line 583 didn't jump to line 584 because the condition on line 583 was never true

584 raise ArchiveError(f"{dists}/Release lists no Packages.xz or Sources.xz") 

585 

586 def entries() -> Iterator[FileInfo]: 

587 for index in indices: 

588 path = os.path.join(dists, index.path) 

589 verify_file(path, index) 

590 log.debug("%s: verified against Release", index.path) 

591 yield from read_index(path) 

592 

593 return collect_pool_files(entries()) 

594 

595 

596def run( 

597 root: str, 

598 suite: str, 

599 *, 

600 source: str | None = None, 

601 rewrite: tuple[str, str] | None = None, 

602 dry_run: bool = False, 

603 limit: int | None = None, 

604 downloader: Downloader | None = None, 

605 out: TextIO = sys.stdout, 

606) -> Report: 

607 """fetch the pool files of `suite` missing below `root` from `source` 

608 

609 Paths of files that are still missing afterwards (or, with 

610 `dry_run`, would be fetched) are written to `out`, one per line. 

611 Raises `ArchiveError` on fatal problems. 

612 """ 

613 files, conflicts = load_pool_files(root, suite) 

614 missing, size_mismatch = check_existing(root, files) 

615 report = Report( 

616 listed=len(files), 

617 present=len(files) - len(missing), 

618 size_mismatch=size_mismatch, 

619 conflicts=conflicts, 

620 ) 

621 abort: str | None = None 

622 if dry_run: 

623 report.not_attempted = [info.path for info in missing] 

624 log.info( 

625 "%d pool files listed: %d present (%d with size mismatch), %d to fetch", 

626 report.listed, 

627 report.present, 

628 len(size_mismatch), 

629 len(missing), 

630 ) 

631 else: 

632 if source is None: 

633 raise ArchiveError("no download source given") 

634 if downloader is None: 634 ↛ 635line 634 didn't jump to line 635 because the condition on line 634 was never true

635 downloader = Downloader() 

636 consecutive_failures = 0 

637 for n, info in enumerate(missing): 

638 if limit is not None and n >= limit: 

639 report.not_attempted.extend(i.path for i in missing[n:]) 

640 log.info("stopping after %d download attempts (--limit)", limit) 

641 break 

642 url = build_url(source, rewrite_path(info.path, rewrite)) 

643 result = downloader.fetch(url, os.path.join(root, info.path), info) 

644 report.record(info, result) 

645 if result.outcome is not Outcome.FAILED: 

646 consecutive_failures = 0 

647 continue 

648 consecutive_failures += 1 

649 if consecutive_failures >= MAX_CONSECUTIVE_FAILURES: 

650 report.not_attempted.extend(i.path for i in missing[n + 1 :]) 

651 abort = ( 

652 f"aborting after {consecutive_failures} consecutive download" 

653 " failures" 

654 ) 

655 break 

656 log.info(report.summary()) 

657 out.writelines(path + "\n" for path in report.still_missing()) 

658 out.flush() 

659 if abort is not None: 

660 raise ArchiveError(abort) 

661 return report 

662 

663 

664def parse_args(argv: list[str]) -> argparse.Namespace: 

665 parser = argparse.ArgumentParser( 

666 description=( 

667 "Download the pool files of an imported suite that are missing" 

668 " below the archive root." 

669 ), 

670 epilog=( 

671 "Paths of files still missing after the run are printed to stdout," 

672 " one per line; progress and warnings go to stderr. Exit status:" 

673 " 0 if all files are present and there were no warnings, 1 if" 

674 " files are missing or warnings were issued, 2 on fatal errors." 

675 ), 

676 ) 

677 parser.add_argument("root", help="archive root containing dists/ and pool/") 

678 parser.add_argument( 

679 "suite", help="suite directory below dists/, e.g. bullseye-security" 

680 ) 

681 parser.add_argument( 

682 "--source", 

683 metavar="URL", 

684 help="base URL to download missing files from (required unless --dry-run)", 

685 ) 

686 parser.add_argument( 

687 "--rewrite-path", 

688 metavar="OLD=NEW", 

689 type=parse_rewrite, 

690 help=( 

691 "replace the prefix OLD of pool paths by NEW when building download" 

692 " URLs, e.g. pool/updates/=pool/ for the main Debian archive" 

693 ), 

694 ) 

695 parser.add_argument( 

696 "--dry-run", 

697 action="store_true", 

698 help="only list the files that would be downloaded", 

699 ) 

700 parser.add_argument( 

701 "--delay", 

702 type=float, 

703 default=0.0, 

704 metavar="SECONDS", 

705 help="pause between downloads (default: %(default)s)", 

706 ) 

707 parser.add_argument( 

708 "--max-retries", 

709 type=int, 

710 default=5, 

711 metavar="N", 

712 help=( 

713 "retries per file for rate limits and transient errors" 

714 " (default: %(default)s)" 

715 ), 

716 ) 

717 parser.add_argument( 

718 "--timeout", 

719 type=float, 

720 default=60.0, 

721 metavar="SECONDS", 

722 help="network timeout for connecting and each read (default: %(default)s)", 

723 ) 

724 parser.add_argument( 

725 "--limit", type=int, metavar="N", help="stop after N download attempts" 

726 ) 

727 verbosity = parser.add_mutually_exclusive_group() 

728 verbosity.add_argument( 

729 "-v", 

730 "--verbose", 

731 action="store_true", 

732 help="also report skipped files and download URLs", 

733 ) 

734 verbosity.add_argument( 

735 "-q", "--quiet", action="store_true", help="only report warnings and errors" 

736 ) 

737 args = parser.parse_args(argv) 

738 if not args.dry_run and args.source is None: 

739 parser.error("--source is required unless --dry-run is given") 

740 if args.delay < 0 or args.max_retries < 0 or args.timeout <= 0: 740 ↛ 741line 740 didn't jump to line 741 because the condition on line 740 was never true

741 parser.error("--delay, --max-retries and --timeout must not be negative") 

742 return args 

743 

744 

745def main(argv: list[str] | None = None) -> int: 

746 args = parse_args(sys.argv[1:] if argv is None else argv) 

747 if args.verbose: 747 ↛ 748line 747 didn't jump to line 748 because the condition on line 747 was never true

748 level = logging.DEBUG 

749 elif args.quiet: 749 ↛ 750line 749 didn't jump to line 750 because the condition on line 749 was never true

750 level = logging.WARNING 

751 else: 

752 level = logging.INFO 

753 logging.basicConfig( 

754 stream=sys.stderr, format="%(levelname)s: %(message)s", level=level 

755 ) 

756 log.setLevel(level) 

757 downloader = Downloader( 

758 timeout=args.timeout, max_retries=args.max_retries, delay=args.delay 

759 ) 

760 try: 

761 report = run( 

762 args.root, 

763 args.suite, 

764 source=args.source, 

765 rewrite=args.rewrite_path, 

766 dry_run=args.dry_run, 

767 limit=args.limit, 

768 downloader=downloader, 

769 out=sys.stdout, 

770 ) 

771 except (ArchiveError, OSError) as e: 771 ↛ 774line 771 didn't jump to line 774

772 log.error("%s", e) 

773 return 2 

774 except KeyboardInterrupt: 

775 log.error("interrupted") 

776 return 130 

777 return 1 if report.still_missing() or report.has_problems() else 0 

778 

779 

780if __name__ == "__main__": 

781 sys.exit(main())