#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Проверка обновлений образов по всем контейнерам и хосту. Почему переписано: прошлая версия смотрела только CT110 и отбрасывала образы, у которых нет RepoDigests (локальные сборки и теги без pull), из-за чего «проверено: 0». Теперь: * обходим ВСЕ LXC и хост; * локальный digest берём из `docker images --digests`; * локальные сборки честно считаем «не сравнить»; * считаем статистику по каждому источнику. """ import json import re import subprocess import urllib.request HOST = None OUT = "/var/lib/hub-agents/updates.json" def sh(cmd, timeout=90): try: r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) return (r.stdout or "").strip() except Exception: return "" def list_cts(): out = sh("pct list | awk 'NR>1 && $2==\"running\"{print $1}'") return [c.strip() for c in out.splitlines() if c.strip().isdigit()] def images(ct): base = f"pct exec {ct} -- " if ct else "" out = sh(base + "docker images --digests --format '{{.Repository}}:{{.Tag}}|{{.Digest}}' 2>/dev/null") res = {} for line in out.splitlines(): if "|" not in line: continue ref, digest = line.split("|", 1) if "" in ref: continue res[ref.strip()] = digest.strip() return res def remote_digest(image): try: name, tag = (image.rsplit(":", 1) + ["latest"])[:2] if "/" not in name: name = "library/" + name host = "registry-1.docker.io" repo = name if repo.startswith("ghcr.io/"): host, repo = "ghcr.io", repo[len("ghcr.io/"):] elif repo.startswith("lscr.io/"): host, repo = "lscr.io", repo[len("lscr.io/"):] elif repo.startswith("quay.io/"): host, repo = "quay.io", repo[len("quay.io/"):] elif repo.startswith("docker.io/"): repo = repo[len("docker.io/"):] if host == "ghcr.io": token_url = f"https://ghcr.io/token?scope=repository:{repo}:pull&service=ghcr.io" elif host == "lscr.io": token_url = f"https://lscr.io/token?scope=repository:{repo}:pull" elif host == "quay.io": token_url = f"https://quay.io/v2/auth?scope=repository:{repo}:pull&service=quay.io" else: token_url = (f"https://auth.docker.io/token?service=registry.docker.io" f"&scope=repository:{repo}:pull") with urllib.request.urlopen(token_url, timeout=12) as r: data = json.loads(r.read()) tok = data.get("token") or data.get("access_token") or "" req = urllib.request.Request( f"https://{host}/v2/{repo}/manifests/{tag}", headers={"Authorization": f"Bearer {tok}", "Accept": "application/vnd.oci.image.index.v1+json," "application/vnd.docker.distribution.manifest.list.v2+json," "application/vnd.oci.image.manifest.v1+json," "application/vnd.docker.distribution.manifest.v2+json"}) with urllib.request.urlopen(req, timeout=15) as r: return r.headers.get("Docker-Content-Digest", "") except Exception: return "" def main(): checked = outdated = nolocal = unreachable = 0 rows = [] targets = [(None, "host")] + [(c, f"CT{c}") for c in list_cts()] for ct, label in targets: imgs = images(ct) for ref, digest in imgs.items(): if ref.endswith(":"): continue if not digest or not digest.startswith("sha256:"): nolocal += 1 continue remote = remote_digest(ref) if not remote: unreachable += 1 continue checked += 1 if remote != digest: outdated += 1 rows.append({"where": label, "image": ref, "local": digest[:19], "remote": remote[:19]}) print(f"проверено: {checked} | обновлений: {outdated} | " f"локальных сборок: {nolocal} | registry недоступен: {unreachable}") for r in rows[:12]: print(f" ↑ {r['image']} ({r['where']})") if len(rows) > 12: print(f" … и ещё {len(rows) - 12}") json.dump(rows, open(OUT, "w"), ensure_ascii=False, indent=1) if rows: body = json.dumps({ "title": "Обновления образов", "message": f"Доступно {len(rows)} обновлений: " + ", ".join(r["image"] for r in rows[:6]), "priority": "low", }).encode() req = urllib.request.Request("http://127.0.0.1:9120/notify", data=body, method="POST", headers={"Content-Type": "application/json"}) try: urllib.request.urlopen(req, timeout=10).read() print("уведомление отправлено") except Exception as e: print("notify:", e) if __name__ == "__main__": main()