Files
mtusi2026lab7-safronov/infra/rotation/same_image.py
T
ricoromaandClaude Opus 5.5 6b637109de fix: address rotation-revocation verify findings
Close handshakes and logins that started before a revocation or a
password change, converge after a failure in any phase, survive a closed
terminal, lock parallel commands and make the drill detect a dead load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:11:17 +03:00

218 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Тот же ли код в образе тега, что у работающих контейнеров (change
rotation-revocation, design, «Уточнения verify»; правило
.claude/rules/rotation.md).
same_image.py <образ> <контейнер>…
Зовёт scripts/rolling-update.sh с ROLLOUT_BUILD=0, когда манифест тега — не
манифест реплик: сборка другим проектом compose меняет только метки образа, а
другой код поочерёдная замена молча выкатила бы. Образ, с которого работает
контейнер, после переезда тега по имени и digest недоступен («No such image»),
поэтому сравнивается то, что есть у контейнера:
- файлы корневой файловой системы целиком — путь, вид, права, владелец,
содержимое (`docker export`): у реплики корень только на чтение, он равен
образу. Контейнер тега только создаётся (`docker create`), не запускается,
и удаляется. Точки монтирования и файлы, которые Docker кладёт сам, — не в
счёт;
- Config: пользователь, команда, точка входа, каталог, порты, тома,
healthcheck, сигнал остановки и окружение, кроме переменных, заданных в
compose.
Только stdlib и синтаксис Python 3.9; значения не печатаются. Коды: 0 — тот же
код; 1 — другой (строка с причиной); 2 — сравнить не удалось.
"""
from __future__ import annotations
import hashlib
import json
import os
import subprocess
import sys
import tarfile
FIELDS = (
"User",
"Cmd",
"Entrypoint",
"WorkingDir",
"ExposedPorts",
"Volumes",
"Healthcheck",
"StopSignal",
"Shell",
)
# кладёт сам Docker в любой контейнер
DOCKER_FILES = (
".dockerenv",
"etc/hostname",
"etc/hosts",
"etc/mtab",
"etc/resolv.conf",
)
DOCKER_DIRS = ("dev", "proc", "sys")
class Unknown(Exception):
"""Сравнить не удалось."""
def output(*args: str) -> str:
result = subprocess.run(
["docker", *args],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
raise Unknown(f"docker {' '.join(args[:2])}: exit {result.returncode}")
return result.stdout
def inspect(kind: str, name: str) -> dict:
return dict(json.loads(output(kind, "inspect", name))[0])
def mounts(container: dict) -> list[str]:
"""Точки монтирования без начального `/`."""
found = [item["Destination"] for item in container.get("Mounts") or []]
found += list((container.get("HostConfig") or {}).get("Tmpfs") or {})
return [path.lstrip("/") for path in found]
def skipped(name: str, places: list[str]) -> bool:
return name in DOCKER_FILES or any(
name == place or name.startswith(place + "/")
for place in (*DOCKER_DIRS, *places)
)
def tree(stream: tarfile.TarFile, places: list[str]) -> dict[str, tuple]:
"""Файлы и ссылки архива: каталоги не в счёт (точки монтирования создаёт
runtime)."""
found: dict[str, tuple] = {}
for item in stream:
name = item.name[2:] if item.name.startswith("./") else item.name
if item.isdir() or skipped(name, places):
continue
digest = ""
body = stream.extractfile(item) if item.isreg() else None
if body is not None:
digest = hashlib.sha256(body.read()).hexdigest()
found[name] = (
item.type,
item.mode,
item.uid,
item.gid,
item.linkname,
digest,
)
return found
def export(container: str, places: list[str]) -> dict[str, tuple]:
proc = subprocess.Popen(
["docker", "export", container],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
try:
with tarfile.open(fileobj=proc.stdout, mode="r|") as stream:
found = tree(stream, places)
except tarfile.TarError:
found = {}
finally:
if proc.stdout is not None:
proc.stdout.close()
code = proc.wait()
if code != 0 or not found:
raise Unknown("docker export failed")
return found
def environment(config: dict, hidden: set[str]) -> dict[str, str]:
pairs = (item.partition("=") for item in config.get("Env") or [])
return {name: value for name, _, value in pairs if name not in hidden}
def config_difference(
image: dict,
container: dict,
hidden: set[str],
) -> str | None:
for field in FIELDS:
if (image.get(field) or None) != (container.get(field) or None):
return f"another {field}"
if environment(image, hidden) != environment(container, hidden):
return "another environment"
return None
def files_difference(
expected: dict[str, tuple],
running: dict[str, tuple],
) -> str | None:
for name in sorted(set(expected) | set(running)):
if expected.get(name) != running.get(name):
return f"another /{name}"
return None
def compose_variables() -> set[str]:
"""Имена переменных сервиса api в модели compose: их задаёт не образ."""
model = json.loads(output("compose", "config", "--format", "json"))
values = model["services"]["api"].get("environment") or {}
return set(values)
def difference(image: str, containers: list[str]) -> str | None:
hidden = compose_variables()
tag = inspect("image", image)["Config"]
described = [inspect("container", item) for item in containers]
for item in described:
found = config_difference(tag, item["Config"], hidden)
if found:
return found
places = sorted({place for item in described for place in mounts(item)})
created = output(
"create",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
image,
).strip()
try:
expected = export(created, places)
finally:
output("rm", "-f", created)
for container in containers:
found = files_difference(expected, export(container, places))
if found:
return found
return None
def main(argv: list[str]) -> int:
image, *containers = argv
try:
found = difference(image, containers)
except (Unknown, OSError, ValueError, KeyError, IndexError) as error:
text = str(error) if isinstance(error, Unknown) else ""
print(f"cannot compare {image}: {text or type(error).__name__}")
return 2
if found:
print(found)
return 1
return 0
if __name__ == "__main__":
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../.."))
sys.exit(main(sys.argv[1:]))