cn-coding-mirrors 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,656 @@
1
+ #!/usr/bin/env python3
2
+ """dpull —— 国内镜像加速的 Docker/OCI 镜像分片下载器
3
+
4
+ 按 registry 协议手工拉取镜像(manifest + 各 layer),layer 走国内镜像源
5
+ 多线程分片下载、逐个 sha256 校验,最后按 `docker save` 的格式合成 tar 并
6
+ `docker load`,等价于 `docker pull` 但不受 ghcr.io / docker.io 直连限速影响。
7
+
8
+ 用法:
9
+ dpull <镜像引用> [选项]
10
+
11
+ 镜像引用:
12
+ ghcr.io/usestrix/strix-sandbox:1.3.0
13
+ docker.io/library/alpine:3.20 (可简写 alpine:3.20 / alpine)
14
+ registry.example.com/team/app@sha256:...
15
+
16
+ 选项:
17
+ -j, --jobs N 每个 layer 的并发分片数 (默认 8)
18
+ -c, --chunk MB 分片大小 (默认 16)
19
+ --platform P 平台 (默认 linux/amd64)
20
+ --mirror H 追加/覆盖镜像源,可重复
21
+ --mirror-only 只用 --mirror 指定的源(不回退官方链)
22
+ --no-mirror 直连官方 registry
23
+ --no-load 只下载并合成 tar,不执行 docker load
24
+ -o, --output FILE 合成后的 tar 路径 (默认缓存目录内)
25
+ --keep-tar 保留 tar 文件
26
+ --cache DIR 内容寻址缓存目录 (默认 ~/.cache/dpull)
27
+ -q, --quiet 只输出结果
28
+ -h, --help 显示帮助
29
+
30
+ 镜像源链 (按顺序尝试,失败自动切换):
31
+ ghcr.io -> ghcr.nju.edu.cn, ghcr.m.daocloud.io, ghcr.io
32
+ docker.io -> docker.m.daocloud.io, docker.1panel.live, hub.rat.dev, registry-1.docker.io
33
+ gcr.io -> gcr.m.daocloud.io, gcr.io
34
+ quay.io -> quay.m.daocloud.io, quay.io
35
+ registry.k8s.io -> k8s.m.daocloud.io, registry.k8s.io
36
+
37
+ 依赖: Python 3.12+(标准库即可)、docker CLI(仅 --no-load 时不强制)
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import hashlib
44
+ import json
45
+ import os
46
+ import re
47
+ import shutil
48
+ import subprocess
49
+ import sys
50
+ import tarfile
51
+ import threading
52
+ import time
53
+ import urllib.error
54
+ import urllib.parse
55
+ import urllib.request
56
+ from concurrent.futures import ThreadPoolExecutor, as_completed, wait
57
+
58
+ if sys.version_info < (3, 8): # noqa: UP036
59
+ sys.exit("dpull: 需要 Python 3.8+(当前 %d.%d)" % sys.version_info[:2])
60
+
61
+ MIRROR_CHAINS = {
62
+ "ghcr.io": ["ghcr.nju.edu.cn", "ghcr.m.daocloud.io", "ghcr.io"],
63
+ "docker.io": ["docker.m.daocloud.io", "docker.1panel.live", "hub.rat.dev",
64
+ "registry-1.docker.io"],
65
+ # parse_ref 会把 docker.io 归一化为 registry-1.docker.io,所以真正生效的是这条
66
+ "registry-1.docker.io": ["docker.m.daocloud.io", "docker.1panel.live", "hub.rat.dev",
67
+ "registry-1.docker.io"],
68
+ "gcr.io": ["gcr.m.daocloud.io", "gcr.io"],
69
+ "quay.io": ["quay.m.daocloud.io", "quay.io"],
70
+ "registry.k8s.io": ["k8s.m.daocloud.io", "registry.k8s.io"],
71
+ "k8s.gcr.io": ["k8s.m.daocloud.io", "registry.k8s.io"],
72
+ }
73
+
74
+ ACCEPT = ", ".join([
75
+ "application/vnd.oci.image.index.v1+json",
76
+ "application/vnd.docker.distribution.manifest.list.v2+json",
77
+ "application/vnd.oci.image.manifest.v1+json",
78
+ "application/vnd.docker.distribution.manifest.v2+json",
79
+ ])
80
+
81
+ _lock = threading.Lock()
82
+ _log_fn = lambda msg: None # noqa: E731 main() 里注入 Log 实例
83
+
84
+
85
+ class _ResumeRejected(Exception):
86
+ """服务端不支持 Range,需要重头下。"""
87
+
88
+
89
+
90
+ def notify(msg: str) -> None:
91
+ _log_fn(msg)
92
+
93
+
94
+ class Log:
95
+ def __init__(self, quiet: bool) -> None:
96
+ self.quiet = quiet
97
+ self.t0 = time.time()
98
+
99
+ def __call__(self, msg: str) -> None:
100
+ if self.quiet:
101
+ return
102
+ with _lock:
103
+ print(f"[{time.time() - self.t0:6.1f}s] {msg}", file=sys.stderr, flush=True)
104
+
105
+ def die(self, msg: str) -> "None":
106
+ print(f"dpull: {msg}", file=sys.stderr, flush=True)
107
+ sys.exit(1)
108
+
109
+
110
+ def parse_ref(ref: str) -> tuple[str, str, str]:
111
+ """拆成 (registry, repository, tag/reference)。"""
112
+ digest = None
113
+ if "@" in ref:
114
+ ref, digest = ref.split("@", 1)
115
+ tag = None
116
+ if digest is None:
117
+ # 最后一段含 ':' 才是 tag(避免误判端口)
118
+ head, sep, tail = ref.rpartition(":")
119
+ if sep and "/" not in tail:
120
+ ref, tag = head, tail
121
+ parts = ref.split("/")
122
+ if len(parts) > 1 and ("." in parts[0] or ":" in parts[0] or parts[0] == "localhost"):
123
+ registry, repo = parts[0], "/".join(parts[1:])
124
+ else:
125
+ registry, repo = "docker.io", ref
126
+ if registry in ("docker.io", "index.docker.io") and "/" not in repo:
127
+ repo = f"library/{repo}"
128
+ if registry == "docker.io":
129
+ registry_api = "registry-1.docker.io"
130
+ else:
131
+ registry_api = registry
132
+ return registry_api, repo, (digest or tag or "latest")
133
+
134
+
135
+ def mirror_chain(registry: str, extra: list[str], disable: bool, only: bool = False) -> list[str]:
136
+ if disable:
137
+ return [registry]
138
+ if only and extra:
139
+ return list(dict.fromkeys(extra))
140
+ chain = list(MIRROR_CHAINS.get(registry, [registry]))
141
+ if not extra:
142
+ return chain
143
+ return list(dict.fromkeys(extra + chain))
144
+
145
+
146
+ class Registry:
147
+ """在一个 host 上做 manifest / blob 访问,token 自动获取并缓存。"""
148
+
149
+ def __init__(self, host: str, registry: str, repo: str) -> None:
150
+ self.host = host
151
+ self.registry = registry # 逻辑 registry(用于 token service)
152
+ self.repo = repo
153
+ self._token: str | None = None
154
+ self._token_tried = False
155
+ self._realm: dict | None = None # 缓存的 Bearer challenge
156
+ self.fails = 0
157
+ self.dead = False # 坏源淘汰标记(403/连续失败)
158
+ self.score = 0.0 # 实测 blob 速度 MB/s
159
+
160
+ def speed_probe(self, digest: str, sample: int = 1 << 18, timeout: int = 6) -> float:
161
+ """拉 sample 字节测速,返回 MB/s(失败返 0)。"""
162
+ hdrs = self._headers({"Range": f"bytes=0-{sample - 1}"})
163
+ t0 = time.time()
164
+ n = 0
165
+ try:
166
+ with self._open(f"/v2/{self.repo}/blobs/{digest}", hdrs, timeout=timeout) as r:
167
+ while n < sample:
168
+ buf = r.read(1 << 16)
169
+ if not buf:
170
+ break
171
+ n += len(buf)
172
+ except Exception: # noqa: BLE001
173
+ return 0.0
174
+ return n / max(time.time() - t0, 1e-6) / 1048576
175
+
176
+ # ---- 健康度 ----
177
+ def note_ok(self) -> None:
178
+ self.fails = 0
179
+
180
+ def note_fail(self, permanent: bool = False) -> None:
181
+ self.fails += 1
182
+ if not self.dead and (permanent or self.fails >= 2):
183
+ self.dead = True
184
+ reason = "拒绝访问" if permanent else f"连续失败 {self.fails} 次"
185
+ notify(f"镜像源 {self.host} {reason},已从分片轮转中移除")
186
+
187
+ # ---- token ----
188
+ @staticmethod
189
+ def _parse_challenge(header: str | None) -> dict | None:
190
+ """解析 `Bearer realm="...",service="...",scope="..."`。"""
191
+ if not header or not header.lower().startswith("bearer"):
192
+ return None
193
+ params = {k.lower(): v for k, v in re.findall(r'(\w+)\s*=\s*"([^"]*)"', header)}
194
+ return params if params.get("realm") else None
195
+
196
+ def _token_from_challenge(self, ch: dict) -> str | None:
197
+ """按 registry challenge 去权威 token 服务换 token(兼容各镜像源)。"""
198
+ q = {"service": ch.get("service", self.host),
199
+ "scope": ch.get("scope") or f"repository:{self.repo}:pull"}
200
+ url = f"{ch['realm']}?{urllib.parse.urlencode(q)}"
201
+ try:
202
+ with urllib.request.urlopen(
203
+ urllib.request.Request(url, headers={"User-Agent": "dpull/1.0"}),
204
+ timeout=8) as r:
205
+ data = json.loads(r.read() or b"{}")
206
+ return data.get("token") or data.get("access_token")
207
+ except Exception: # noqa: BLE001
208
+ return None
209
+
210
+ def token(self, refresh: bool = False) -> str | None:
211
+ if self._token_tried and not refresh:
212
+ return self._token
213
+ self._token_tried = True
214
+
215
+ # 1) 探测镜像源自己的 challenge(最权威):GET /v2/ 无认证即可用则不拿 token
216
+ try:
217
+ with urllib.request.urlopen(
218
+ urllib.request.Request(f"https://{self.host}/v2/",
219
+ headers={"User-Agent": "dpull/1.0"}),
220
+ timeout=8) as r:
221
+ if r.status == 200:
222
+ self._token = None # 匿名开放,不需要 token
223
+ return None
224
+ except urllib.error.HTTPError as e:
225
+ ch = self._parse_challenge(e.headers.get("WWW-Authenticate"))
226
+ if ch:
227
+ self._realm = ch
228
+ tok = self._token_from_challenge(ch)
229
+ if tok:
230
+ self._token = tok
231
+ return tok
232
+ except Exception: # noqa: BLE001
233
+ pass
234
+
235
+ # 2) 退路:官方 registry 的 token 端点(仅当镜像源没说清 realm 时)
236
+ scope = f"scope=repository:{self.repo}:pull"
237
+ for url in (f"https://{self.registry}/token?service={self.registry}&{scope}",):
238
+ try:
239
+ with urllib.request.urlopen(urllib.request.Request(url), timeout=8) as r:
240
+ data = json.loads(r.read() or b"{}")
241
+ tok = data.get("token") or data.get("access_token")
242
+ if tok:
243
+ self._token = tok
244
+ return tok
245
+ except Exception: # noqa: BLE001
246
+ continue
247
+
248
+ # 3) ghcr 部分镜像接受固定匿名 token
249
+ self._token = "djE6" if self.registry == "ghcr.io" else None
250
+ return self._token
251
+
252
+ def _headers(self, extra: dict | None = None) -> dict:
253
+ h = {"User-Agent": "dpull/1.0"}
254
+ tok = self.token()
255
+ if tok:
256
+ h["Authorization"] = f"Bearer {tok}"
257
+ if extra:
258
+ h.update(extra)
259
+ return h
260
+
261
+ def _open(self, path: str, headers: dict, method: str = "GET", retry_auth: bool = True,
262
+ timeout: int = 60):
263
+ url = f"https://{self.host}{path}"
264
+ req = urllib.request.Request(url, headers=headers, method=method)
265
+ try:
266
+ return urllib.request.urlopen(req, timeout=timeout)
267
+ except urllib.error.HTTPError as e:
268
+ if e.code not in (401, 403) or not retry_auth:
269
+ raise
270
+ base = {k: v for k, v in headers.items() if k != "Authorization"}
271
+ # 401 带 Bearer challenge 时按 realm 换 token(镜像源各有自己的 realm)
272
+ ch = self._parse_challenge(e.headers.get("WWW-Authenticate"))
273
+ if ch:
274
+ self._realm = ch
275
+ tok = self._token_from_challenge(ch)
276
+ if tok:
277
+ self._token, self._token_tried = tok, True
278
+ if not self._token:
279
+ self._token_tried = False
280
+ self.token(refresh=True)
281
+ req = urllib.request.Request(
282
+ url, headers={**base, **({"Authorization": f"Bearer {self._token}"}
283
+ if self._token else {})}, method=method)
284
+ return urllib.request.urlopen(req, timeout=timeout)
285
+
286
+ # ---- manifest ----
287
+ def manifest(self, reference: str) -> tuple[dict, str, str]:
288
+ with self._open(f"/v2/{self.repo}/manifests/{reference}",
289
+ self._headers({"Accept": ACCEPT})) as r:
290
+ raw = r.read()
291
+ digest = r.headers.get("Docker-Content-Digest") or \
292
+ "sha256:" + hashlib.sha256(raw).hexdigest()
293
+ ctype = r.headers.get("Content-Type", "").split(";")[0]
294
+ return json.loads(raw), digest, ctype
295
+
296
+ def blob_size(self, digest: str) -> int | None:
297
+ try:
298
+ with self._open(f"/v2/{self.repo}/blobs/{digest}",
299
+ self._headers({"Range": "bytes=0-0"})) as r:
300
+ cr = r.headers.get("Content-Range")
301
+ if cr and "/" in cr:
302
+ return int(cr.rsplit("/", 1)[1])
303
+ cl = r.headers.get("Content-Length")
304
+ return int(cl) if cl else None
305
+ except Exception:
306
+ try:
307
+ with self._open(f"/v2/{self.repo}/blobs/{digest}",
308
+ self._headers(), method="HEAD") as r:
309
+ cl = r.headers.get("Content-Length")
310
+ return int(cl) if cl else None
311
+ except Exception:
312
+ return None
313
+
314
+ def fetch(self, digest: str, dest: str, start: int | None = None,
315
+ end: int | None = None, max_tries: int = 1, timeout: int = 12) -> int:
316
+ """下载(可指定字节区间)到 dest,返回 dest 中的总字节数。
317
+
318
+ 支持断点续传:dest 已有内容时用 Range 从断点继续,GFW 卡死的连接
319
+ 只需重试而不是把整片 16MB 重头拉一遍。
320
+ """
321
+ last = None
322
+ for attempt in range(max_tries):
323
+ have = 0
324
+ if start is not None and end is not None and os.path.exists(dest):
325
+ have = os.path.getsize(dest)
326
+ if have > end - start + 1: # 垃圾文件,重来
327
+ have = 0
328
+ hdrs = self._headers()
329
+ if start is not None and end is not None:
330
+ hdrs["Range"] = f"bytes={start + have}-{end}"
331
+ wrote = 0
332
+ try:
333
+ with self._open(f"/v2/{self.repo}/blobs/{digest}", hdrs, timeout=timeout) as r:
334
+ if have and getattr(r, "status", 200) != 206:
335
+ # 服务端忽略了 Range,不能追加写
336
+ if os.path.exists(dest):
337
+ os.remove(dest)
338
+ raise _ResumeRejected()
339
+ with open(dest, "ab" if have else "wb") as f:
340
+ while True:
341
+ buf = r.read(1 << 20)
342
+ if not buf:
343
+ break
344
+ f.write(buf)
345
+ wrote += len(buf)
346
+ self.note_ok()
347
+ return have + wrote
348
+ except _ResumeRejected:
349
+ time.sleep(1)
350
+ continue
351
+ except urllib.error.HTTPError as e: # 403/404 没必要再试
352
+ last = e
353
+ self.note_fail(permanent=e.code in (401, 403, 404))
354
+ time.sleep(1 + attempt)
355
+ except Exception as e: # noqa: BLE001
356
+ last = e
357
+ if wrote: # 已经收到数据,说明源本身可用,只是连接被掐
358
+ self.note_ok()
359
+ else:
360
+ self.note_fail()
361
+ time.sleep(1 + attempt)
362
+ raise RuntimeError(f"{self.host} 下载失败: {last}")
363
+
364
+
365
+ def probe_mirrors(regs: list["Registry"], log: "Log", digest: str | None = None,
366
+ sample: int = 1 << 18, timeout: int = 6,
367
+ budget: float = 6.0) -> list["Registry"]:
368
+ """实测每个镜像源拉 blob 的速度并排名。
369
+
370
+ 只看 /v2/ 能不能连是不够的:ghcr.io 直连能过 /v2/,blob 却被重定向到被封的
371
+ GitHub CDN 慢慢滴,只会把分片卡死。这里真的拉 sample 字节测速;
372
+ 整体限时 budget 秒,拖后腿的源直接排到最后而不是干等。
373
+ """
374
+ if len(regs) <= 1 or not digest:
375
+ return regs
376
+
377
+ def measure(r: "Registry") -> float:
378
+ return r.speed_probe(digest, sample=sample, timeout=timeout)
379
+
380
+ ex = ThreadPoolExecutor(max_workers=len(regs))
381
+ futs = {ex.submit(measure, r): r for r in regs}
382
+ done, pending = wait(futs, timeout=budget)
383
+ for f in done:
384
+ r = futs[f]
385
+ try:
386
+ r.score = f.result()
387
+ except Exception: # noqa: BLE001
388
+ r.score = 0.0
389
+ for f in pending:
390
+ futs[f].score = -1.0 # 超时:不标记为死源,只排到最后
391
+ ex.shutdown(wait=False)
392
+
393
+ for r in regs:
394
+ if r.score == 0.0:
395
+ r.note_fail(permanent=True)
396
+ alive = [r for r in regs if not r.dead]
397
+ if not alive:
398
+ for r in regs:
399
+ r.dead, r.fails = False, 0
400
+ log("测速全部失败,保留所有镜像源重试")
401
+ return regs
402
+ alive.sort(key=lambda r: -r.score)
403
+ log("测速排名: " + ", ".join(
404
+ f"{r.host} {'超时' if r.score < 0 else f'{r.score:.1f} MB/s'}" for r in alive))
405
+ return alive
406
+
407
+
408
+ def sha256_file(path: str) -> str:
409
+ h = hashlib.sha256()
410
+ with open(path, "rb") as f:
411
+ for buf in iter(lambda: f.read(1 << 20), b""):
412
+ h.update(buf)
413
+ return h.hexdigest()
414
+
415
+
416
+ def download_blob(blob_digest: str, size: int, mirrors: list[Registry], cache_dir: str,
417
+ jobs: int, chunk: int, log: Log) -> str:
418
+ """下载并校验一个 blob,返回缓存中的路径(内容寻址)。"""
419
+ hexd = blob_digest.split(":", 1)[1]
420
+ final = os.path.join(cache_dir, "blobs", "sha256", hexd)
421
+ if os.path.exists(final):
422
+ return final
423
+ os.makedirs(os.path.dirname(final), exist_ok=True)
424
+ tmpd = os.path.join(cache_dir, "tmp", hexd)
425
+ os.makedirs(tmpd, exist_ok=True)
426
+
427
+ if size == 0:
428
+ log(f" {blob_digest[:19]}… 大小为 0,直接取回")
429
+ n = next((m for m in mirrors if not m.dead), mirrors[0]).fetch(
430
+ blob_digest, final + ".tmp", max_tries=5)
431
+ os.replace(final + ".tmp", final)
432
+ return final
433
+ if size < chunk * (1 << 20) * 2: # 小文件单连接
434
+ nparts, chunk_bytes = 1, size
435
+ else:
436
+ chunk_bytes = chunk << 20
437
+ nparts = (size + chunk_bytes - 1) // chunk_bytes
438
+
439
+ def part_path(i: int) -> str:
440
+ return os.path.join(tmpd, f"{i:04d}.part")
441
+
442
+ def get_part(i: int) -> None:
443
+ start = i * chunk_bytes
444
+ end = min(start + chunk_bytes, size) - 1
445
+ expect = end - start + 1
446
+ p = part_path(i)
447
+ if os.path.exists(p) and os.path.getsize(p) == expect:
448
+ return
449
+ # 上次进程被杀时可能已经把分片拉完,只是没来得及改名
450
+ if os.path.exists(p + ".tmp") and os.path.getsize(p + ".tmp") == expect:
451
+ os.replace(p + ".tmp", p)
452
+ return
453
+ last = None
454
+ for attempt in range(40):
455
+ # 粘住测速最快的源,只有它持续拿不到字节时才轮到下一个
456
+ pool = [m for m in mirrors if not m.dead] or mirrors
457
+ reg = pool[min(attempt, len(pool) - 1)]
458
+ try:
459
+ reg.fetch(blob_digest, p + ".tmp", start, end if nparts > 1 else None,
460
+ max_tries=1)
461
+ got = os.path.getsize(p + ".tmp") if os.path.exists(p + ".tmp") else 0
462
+ if got == expect:
463
+ os.replace(p + ".tmp", p)
464
+ return
465
+ last = f"只收到 {got}/{expect} 字节"
466
+ except Exception as e: # noqa: BLE001
467
+ last = e
468
+ time.sleep(min(1 + attempt, 3))
469
+ raise RuntimeError(f"分片 {i} 失败: {last}")
470
+
471
+ workers = min(jobs, max(nparts, 1))
472
+ with ThreadPoolExecutor(max_workers=workers) as ex:
473
+ futs = {ex.submit(get_part, i): i for i in range(nparts)}
474
+ for f in as_completed(futs):
475
+ f.result()
476
+
477
+ joined = os.path.join(tmpd, "joined")
478
+ with open(joined, "wb") as out:
479
+ for i in range(nparts):
480
+ with open(part_path(i), "rb") as f:
481
+ shutil.copyfileobj(f, out, 1 << 20)
482
+ got = os.path.getsize(joined)
483
+ if got != size:
484
+ raise RuntimeError(f"大小不符 {got} != {size}")
485
+ if sha256_file(joined) != hexd:
486
+ raise RuntimeError("sha256 校验失败,已丢弃该 blob")
487
+ os.replace(joined, final)
488
+ shutil.rmtree(tmpd, ignore_errors=True)
489
+ return final
490
+
491
+
492
+ def main() -> int:
493
+ ap = argparse.ArgumentParser(add_help=True, description="国内镜像加速的镜像分片下载器")
494
+ ap.add_argument("image")
495
+ ap.add_argument("-j", "--jobs", type=int, default=8)
496
+ ap.add_argument("-c", "--chunk", type=int, default=16, help="分片大小 MB")
497
+ ap.add_argument("--platform", default="linux/amd64")
498
+ ap.add_argument("--mirror", action="append", default=[])
499
+ ap.add_argument("--mirror-only", action="store_true")
500
+ ap.add_argument("--no-mirror", action="store_true")
501
+ ap.add_argument("--no-load", action="store_true")
502
+ ap.add_argument("-o", "--output")
503
+ ap.add_argument("--keep-tar", action="store_true")
504
+ ap.add_argument("--cache", default=os.path.expanduser("~/.cache/dpull"))
505
+ ap.add_argument("-q", "--quiet", action="store_true")
506
+ args = ap.parse_args()
507
+
508
+ log = Log(args.quiet)
509
+ global _log_fn
510
+ _log_fn = log
511
+ registry, repo, reference = parse_ref(args.image)
512
+ extra_mirrors = list(args.mirror) or os.environ.get("DPULL_MIRRORS", "").split()
513
+ hosts = mirror_chain(registry, extra_mirrors, args.no_mirror, args.mirror_only)
514
+ regs = [Registry(h, registry, repo) for h in hosts]
515
+ log(f"镜像: {registry}/{repo}:{reference}")
516
+ log(f"镜像源链: {', '.join(hosts)}")
517
+
518
+ # 1) 取 manifest(自动跳过不可用镜像源)
519
+ manifest = digest = None
520
+ errors = []
521
+ for reg in regs:
522
+ try:
523
+ m, d, ctype = reg.manifest(reference)
524
+ manifest, digest = m, d
525
+ log(f"manifest 来自 {reg.host} ({ctype or 'unknown'})")
526
+ break
527
+ except Exception as e: # noqa: BLE001
528
+ errors.append(f"{reg.host}: {e}")
529
+ if manifest is None:
530
+ log.die("所有镜像源都取不到 manifest:\n " + "\n ".join(errors))
531
+
532
+ # 2) manifest list -> 选出目标平台
533
+ mt = (manifest.get("mediaType") or "") + (ctype or "")
534
+ if "index" in mt or "manifest.list" in mt or manifest.get("manifests"):
535
+ want_os, want_arch = (args.platform.split("/") + ["amd64"])[:2]
536
+ pick = None
537
+ for m in manifest.get("manifests", []):
538
+ p = m.get("platform") or {}
539
+ if p.get("os") == want_os and p.get("architecture") == want_arch:
540
+ pick = m
541
+ break
542
+ if pick is None:
543
+ log.die(f"manifest list 里没有 {args.platform}")
544
+ log(f"平台 {args.platform} -> {pick['digest'][:19]}…")
545
+ digest = pick["digest"]
546
+ got = None
547
+ for reg in regs:
548
+ try:
549
+ got = reg.manifest(digest)
550
+ break
551
+ except Exception:
552
+ continue
553
+ if got is None:
554
+ log.die("取平台 manifest 失败")
555
+ manifest = got[0]
556
+
557
+ config_descriptor = manifest.get("config") or {}
558
+ layers = manifest.get("layers") or []
559
+ total = sum(int(l.get("size") or 0) for l in layers) + int(config_descriptor.get("size") or 0)
560
+ log(f"config + {len(layers)} 个 layer,合计 {total / 1048576:.1f} MB")
561
+
562
+ # 3) 下载所有 blob(分片并发)
563
+ # 先用一个真实大 layer 给各镜像源测速,排掉黑洞源并选出最快的
564
+ probe_blob = max((b for b in layers if int(b.get("size") or 0) > (1 << 20)),
565
+ key=lambda b: int(b.get("size") or 0), default=None)
566
+ regs = probe_mirrors(regs, log, (probe_blob or config_descriptor).get("digest"))
567
+ os.makedirs(args.cache, exist_ok=True)
568
+ blobs = [config_descriptor] + list(layers)
569
+ paths: dict[str, str] = {}
570
+ for idx, b in enumerate(blobs, 1):
571
+ d, s = b["digest"], int(b.get("size") or 0)
572
+ name = d[:19]
573
+ cached = os.path.join(args.cache, "blobs", "sha256", d.split(":", 1)[1])
574
+ if os.path.exists(cached):
575
+ log(f"[{idx}/{len(blobs)}] {name}… 已在缓存")
576
+ else:
577
+ log(f"[{idx}/{len(blobs)}] {name}… 开始 ({s / 1048576:.1f} MB, {args.jobs} 分片)")
578
+ try:
579
+ paths[d] = download_blob(d, s, regs, args.cache, args.jobs, args.chunk, log)
580
+ except Exception as e: # noqa: BLE001
581
+ log.die(f"blob {d} 下载失败: {e}")
582
+
583
+ # 4) 合成 docker save 兼容 tar(blobs/ + manifest.json + oci 布局)
584
+ out = args.output or os.path.join(
585
+ args.cache, "images",
586
+ f"{registry.replace('/', '_')}_{repo.replace('/', '_')}_{reference.replace(':', '_')}.tar")
587
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
588
+ manifest_bytes = json.dumps(manifest, separators=(",", ":")).encode()
589
+ manifest_digest = "sha256:" + hashlib.sha256(manifest_bytes).hexdigest()
590
+ tag_ref = args.image if "@" not in args.image else f"{registry}/{repo}:{reference}"
591
+
592
+ log(f"合成 tar: {out}")
593
+ mpath = os.path.join(args.cache, "blobs", "sha256", manifest_digest.split(":", 1)[1])
594
+ if not os.path.exists(mpath):
595
+ with open(mpath, "wb") as f:
596
+ f.write(manifest_bytes)
597
+
598
+ cfg = config_descriptor["digest"]
599
+ legacy = [{
600
+ "Config": f"blobs/sha256/{cfg.split(':', 1)[1]}",
601
+ "RepoTags": [tag_ref],
602
+ "Layers": [f"blobs/sha256/{l['digest'].split(':', 1)[1]}" for l in layers],
603
+ }]
604
+ index = {
605
+ "schemaVersion": 2,
606
+ "mediaType": "application/vnd.oci.image.index.v1+json",
607
+ "manifests": [{
608
+ "mediaType": manifest.get("mediaType", "application/vnd.oci.image.manifest.v1+json"),
609
+ "digest": manifest_digest,
610
+ "size": len(manifest_bytes),
611
+ "platform": {"architecture": args.platform.split("/")[1],
612
+ "os": args.platform.split("/")[0]},
613
+ "annotations": {"org.opencontainers.image.ref.name": tag_ref},
614
+ }],
615
+ }
616
+
617
+ with tarfile.open(out, "w", format=tarfile.PAX_FORMAT) as tf:
618
+ def add_bytes(name: str, data: bytes) -> None:
619
+ import io
620
+ ti = tarfile.TarInfo(name)
621
+ ti.size = len(data)
622
+ ti.mtime = int(time.time())
623
+ tf.addfile(ti, io.BytesIO(data))
624
+
625
+ add_bytes("oci-layout", json.dumps({"imageLayoutVersion": "1.0.0"}).encode())
626
+ add_bytes("index.json", json.dumps(index, separators=(",", ":")).encode())
627
+ add_bytes("manifest.json", json.dumps(legacy, separators=(",", ":")).encode())
628
+ for d, p in list(paths.items()) + [(manifest_digest, mpath)]:
629
+ tf.add(p, arcname=f"blobs/sha256/{d.split(':', 1)[1]}", recursive=False)
630
+
631
+ log(f"tar 完成: {out} ({os.path.getsize(out) / 1048576:.1f} MB)")
632
+
633
+ if args.no_load:
634
+ print(out)
635
+ return 0
636
+
637
+ log("docker load …")
638
+ r = subprocess.run(["docker", "load", "-i", out], capture_output=True, text=True)
639
+ if r.returncode != 0:
640
+ log(f"docker load 失败: {r.stderr.strip()[:400]}")
641
+ print(out)
642
+ return 1
643
+ log(r.stdout.strip() or "已加载")
644
+ if not args.keep_tar:
645
+ os.remove(out)
646
+ log("已删除临时 tar (--keep-tar 可保留)")
647
+ print(tag_ref)
648
+ return 0
649
+
650
+
651
+ if __name__ == "__main__":
652
+ try:
653
+ sys.exit(main())
654
+ except KeyboardInterrupt:
655
+ print("dpull: 已中断", file=sys.stderr)
656
+ sys.exit(130)