|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Sync Docker Hub repository descriptions for the rsyslog image family. |
| 3 | +
|
| 4 | +By default the script runs in dry-run mode and prints the intended updates. |
| 5 | +Use --apply to write metadata to Docker Hub. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import argparse |
| 11 | +import base64 |
| 12 | +import binascii |
| 13 | +import json |
| 14 | +import os |
| 15 | +from pathlib import Path |
| 16 | +import sys |
| 17 | +import urllib.error |
| 18 | +import urllib.request |
| 19 | + |
| 20 | + |
| 21 | +HUB_LOGIN_URL = "https://hub.docker.com/v2/users/login/" |
| 22 | +HUB_REPO_URL = "https://hub.docker.com/v2/repositories/{namespace}/{repo}/" |
| 23 | +DEFAULT_NAMESPACE = "rsyslog" |
| 24 | +DEFAULT_METADATA_FILE = Path(__file__).with_name("dockerhub_metadata.json") |
| 25 | + |
| 26 | + |
| 27 | +def load_metadata(path: Path) -> dict[str, dict[str, str]]: |
| 28 | + return json.loads(path.read_text()) |
| 29 | + |
| 30 | + |
| 31 | +def load_credentials() -> tuple[str, str]: |
| 32 | + username = os.getenv("DOCKERHUB_USERNAME") |
| 33 | + password = os.getenv("DOCKERHUB_PASSWORD") |
| 34 | + if username and password: |
| 35 | + return username, password |
| 36 | + |
| 37 | + cfg_path = Path.home() / ".docker" / "config.json" |
| 38 | + if not cfg_path.exists(): |
| 39 | + raise RuntimeError( |
| 40 | + "No Docker Hub credentials found. Set DOCKERHUB_USERNAME and " |
| 41 | + "DOCKERHUB_PASSWORD or login with docker first." |
| 42 | + ) |
| 43 | + |
| 44 | + cfg = json.loads(cfg_path.read_text()) |
| 45 | + auths = cfg.get("auths", {}) |
| 46 | + auth = auths.get("https://index.docker.io/v1/", {}).get("auth") |
| 47 | + if not auth: |
| 48 | + raise RuntimeError( |
| 49 | + "Docker config does not contain https://index.docker.io/v1/ auth." |
| 50 | + ) |
| 51 | + |
| 52 | + try: |
| 53 | + decoded = base64.b64decode(auth).decode() |
| 54 | + except (binascii.Error, UnicodeDecodeError) as err: |
| 55 | + raise RuntimeError("Docker config auth for Docker Hub is malformed.") from err |
| 56 | + |
| 57 | + if ":" not in decoded: |
| 58 | + raise RuntimeError("Docker config auth for Docker Hub is malformed.") |
| 59 | + |
| 60 | + return tuple(decoded.split(":", 1)) |
| 61 | + |
| 62 | + |
| 63 | +def hub_request( |
| 64 | + url: str, token: str | None = None, method: str = "GET", payload: dict | None = None |
| 65 | +) -> dict: |
| 66 | + data = None if payload is None else json.dumps(payload).encode() |
| 67 | + req = urllib.request.Request(url, data=data, method=method) |
| 68 | + req.add_header("Content-Type", "application/json") |
| 69 | + if token: |
| 70 | + req.add_header("Authorization", f"JWT {token}") |
| 71 | + with urllib.request.urlopen(req, timeout=30) as resp: |
| 72 | + return json.loads(resp.read().decode()) |
| 73 | + |
| 74 | + |
| 75 | +def login() -> str: |
| 76 | + username, password = load_credentials() |
| 77 | + resp = hub_request(HUB_LOGIN_URL, method="POST", payload={"username": username, "password": password}) |
| 78 | + token = resp.get("token") |
| 79 | + if not token: |
| 80 | + raise RuntimeError("Docker Hub login succeeded but no token was returned.") |
| 81 | + return token |
| 82 | + |
| 83 | + |
| 84 | +def normalize_repo_selection(selected: list[str] | None, metadata: dict[str, dict[str, str]]) -> list[str]: |
| 85 | + if not selected: |
| 86 | + return sorted(metadata.keys()) |
| 87 | + missing = [name for name in selected if name not in metadata] |
| 88 | + if missing: |
| 89 | + raise RuntimeError(f"Metadata file does not define repos: {', '.join(missing)}") |
| 90 | + return selected |
| 91 | + |
| 92 | + |
| 93 | +def main() -> int: |
| 94 | + parser = argparse.ArgumentParser(description=__doc__) |
| 95 | + parser.add_argument("--apply", action="store_true", help="Write metadata to Docker Hub.") |
| 96 | + parser.add_argument("--namespace", default=DEFAULT_NAMESPACE, help="Docker Hub namespace. Default: rsyslog") |
| 97 | + parser.add_argument( |
| 98 | + "--metadata-file", |
| 99 | + default=str(DEFAULT_METADATA_FILE), |
| 100 | + help="Path to the JSON metadata file.", |
| 101 | + ) |
| 102 | + parser.add_argument( |
| 103 | + "--repo", |
| 104 | + action="append", |
| 105 | + help="Limit sync to one or more repos defined in the metadata file.", |
| 106 | + ) |
| 107 | + args = parser.parse_args() |
| 108 | + |
| 109 | + metadata_file = Path(args.metadata_file) |
| 110 | + metadata = load_metadata(metadata_file) |
| 111 | + repos = normalize_repo_selection(args.repo, metadata) |
| 112 | + |
| 113 | + token = login() |
| 114 | + |
| 115 | + for repo in repos: |
| 116 | + payload = metadata[repo] |
| 117 | + url = HUB_REPO_URL.format(namespace=args.namespace, repo=repo) |
| 118 | + current = hub_request(url, token=token) |
| 119 | + summary = { |
| 120 | + "repo": f"{args.namespace}/{repo}", |
| 121 | + "current_description": current.get("description") or "", |
| 122 | + "new_description": payload["description"], |
| 123 | + "apply": args.apply, |
| 124 | + } |
| 125 | + print(json.dumps(summary, ensure_ascii=True)) |
| 126 | + if args.apply: |
| 127 | + updated = hub_request(url, token=token, method="PATCH", payload=payload) |
| 128 | + print( |
| 129 | + json.dumps( |
| 130 | + { |
| 131 | + "repo": f"{args.namespace}/{repo}", |
| 132 | + "updated_description": updated.get("description") or "", |
| 133 | + "has_full_description": updated.get("full_description") is not None, |
| 134 | + }, |
| 135 | + ensure_ascii=True, |
| 136 | + ) |
| 137 | + ) |
| 138 | + |
| 139 | + return 0 |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + try: |
| 144 | + raise SystemExit(main()) |
| 145 | + except urllib.error.HTTPError as err: |
| 146 | + print(f"HTTP error from Docker Hub: {err.code} {err.reason}", file=sys.stderr) |
| 147 | + raise |
| 148 | + except Exception as err: # pragma: no cover - CLI path |
| 149 | + print(f"ERROR: {err}", file=sys.stderr) |
| 150 | + raise SystemExit(1) |
0 commit comments