Files
computer-playbook/cli/contributing/mirror/sync/__main__.py
T
kevinveenbirkenbachandClaude Opus 4.7 a26bfc4e94 refactor(cli): reorg admin/contributing tree + per-folder help system
Module moves (with imports, paths, argv literals, scripts, docs, and
parents[N] formulas updated in lockstep):

- cli/deploy             -> cli/administration/deploy
- cli/validate/inventory -> cli/administration/inventory/validate
- cli/vault              -> cli/administration/secrets/vault
- cli/administration/inventory/encrypt -> cli/administration/secrets/seal
- cli/mirror             -> cli/contributing/mirror

The new cli/administration/secrets cluster collocates the whole-file
ansible-vault wrapper next to the inventory-aware per-field sealer.
The user-facing CLI subcommand paths follow the package layout, e.g.
"infinito administration deploy dedicated <inv>" and
"infinito administration inventory validate <inv>".

Help system redesign in cli/core/{discovery,help,app}.py:

- Discovery now distinguishes runnable commands (directories with
  __main__.py) from category folders (directories that only group
  further commands). Empty support packages are filtered out.
- Each category folder MAY carry a README.md; its H1 heading is used
  as the title and its first paragraph as the one-line description in
  the help output.
- "infinito" / "infinito --help" prints only the top-level entries
  (one level deep). "infinito <category>" navigates into a folder and
  shows its sub-folders and commands one level deep, with the README
  title as the page heading and the invocation as a dim subtitle.
- New "--tree [N]" flag walks the tree under the (optional) path
  prefix recursively. N caps the depth (1-based); omit N for an
  unbounded walk. The output uses Unicode tree connectors, an emoji
  per entry (folder for categories, gear for commands), a globally
  aligned description column, and multi-line wrapped descriptions
  with tree-continuity bars on continuation lines.
- Category and command listings use the full invocation
  ("infinito meta callorder") rather than the bare leaf name, so the
  output is copy-pasteable.

Convention doc + 17 CLI READMEs:

- New docs/contributing/artefact/files/cli/readme_md.md describes the
  H1+paragraph layout the help system reads, and how it differs from
  role/docs READMEs.
- README.md added for cli/{administration, build, contributing, meta}
  and their immediate sub-folders, plus cli/meta/roles/applications
  and its resolution sub-folder. Each follows the "title with trailing
  emoji + single descriptive paragraph" convention.

Mirror resolver/sync description strings (the help system reads them
from argparse --help output) added so they no longer surface as
"options:" in the global index. cli/mirror/cleanup already had a
description and is unchanged.

Fixes uncovered by the move:

- import unittest.mock added to four dedicated-deploy tests so
  unittest.mock.patch resolves under stdlib unittest discovery
  (Python 3.13 no longer surfaces unittest.mock through "import
  unittest" alone).
- parents[N] index in the new
  cli/administration/inventory/validate/__init__.py corrected from
  3 to 4 to match the deeper layout.
- test_paths.INVENTORY_VALIDATOR_PATH assertion and test_runner
  substring assertions updated to match the new validator path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 20:17:09 +02:00

140 lines
4.1 KiB
Python

from __future__ import annotations
import argparse
import subprocess
import sys
import time
from pathlib import Path
from cli.contributing.mirror.providers import GHCRProvider
from utils.docker.image.discovery import iter_role_images
def _validate_positive_int(value: str) -> int:
try:
n = int(value)
except ValueError as e:
raise argparse.ArgumentTypeError("must be an integer") from e
if n <= 0:
raise argparse.ArgumentTypeError("must be > 0")
return n
def _throttle_before_next_copy(
*, images_per_hour: int | None, last_start_ts: float | None
) -> float:
"""
If images_per_hour is set, ensure at least (3600 / images_per_hour) seconds
have elapsed since last_start_ts before returning.
Returns the (possibly updated) start timestamp for the next copy.
"""
if not images_per_hour:
return time.monotonic()
min_interval = 3600.0 / float(images_per_hour)
now = time.monotonic()
if last_start_ts is not None:
elapsed = now - last_start_ts
remaining = min_interval - elapsed
if remaining > 0:
print(
f"[mirror] throttling: sleeping {remaining:.1f}s "
f"(limit={images_per_hour} images/hour)",
flush=True,
)
time.sleep(remaining)
return time.monotonic()
def main() -> int:
parser = argparse.ArgumentParser(
description=(
"Mirror every role-declared image to the configured GHCR registry, "
"optionally throttled and optionally skipping already-mirrored "
"tags."
),
)
parser.add_argument("--repo-root", default=".")
GHCRProvider.add_args(parser)
parser.add_argument(
"--only-missing",
action="store_true",
help="Mirror only images that do not exist in the destination registry.",
)
parser.add_argument(
"--images-per-hour",
type=_validate_positive_int,
default=None,
help="Optional throttle: max images to mirror per hour (best-effort).",
)
args = parser.parse_args()
provider = GHCRProvider.from_args(args)
repo_root = Path(args.repo_root).resolve()
failures: list[str] = []
total = 0
last_start_ts: float | None = None
for img in iter_role_images(repo_root):
# Optional throttling (only when --images-per-hour is set)
last_start_ts = _throttle_before_next_copy(
images_per_hour=args.images_per_hour,
last_start_ts=last_start_ts,
)
total += 1
src = f"docker://{img.source}"
dest = f"docker://{provider.image_base(img)}:{img.version}"
label = f"{img.role}:{img.service} ({img.name}:{img.version})"
try:
if args.only_missing and provider.tag_exists(img):
print(
f"[mirror] {label}: destination exists, skipping ({dest})",
flush=True,
)
continue
print(f"[mirror] {label}: {src} -> {dest}", flush=True)
provider.mirror(img)
except subprocess.CalledProcessError as e:
# keep going, but remember the failure
msg = (
f"{label}: FAILED (exit={e.returncode})\n"
f" cmd: {' '.join(map(str, e.cmd))}"
)
failures.append(msg)
print(
f"[mirror] {label}: FAILED, continuing...",
file=sys.stderr,
flush=True,
)
except Exception as e:
msg = f"{label}: FAILED (unexpected error: {e!r})"
failures.append(msg)
print(
f"[mirror] {label}: FAILED (unexpected), continuing...",
file=sys.stderr,
flush=True,
)
if failures:
print("\n[mirror] SUMMARY: some images failed:", file=sys.stderr)
for f in failures:
print(f"- {f}", file=sys.stderr)
print(f"\n[mirror] Result: {len(failures)}/{total} failed.", file=sys.stderr)
return 1
print(f"\n[mirror] Result: {total}/{total} succeeded.")
return 0
if __name__ == "__main__":
raise SystemExit(main())