CI / check (pull_request) Successful in 22s
The record was taken right before the engine's swap. Since then the database step and the broker replace their containers earlier, so a new PostgreSQL or Valkey image left the old one on the host for good; docker image prune -af used to take it. It also listed only the engine services, so postgres (behind its compose profile), apt-cacher-ng, signal-api and the retired registry were never recorded. deploy.sh now records the images of every container of the compose project netork, by its label, before the database step, and keeps only image IDs: they are expanded into the command that removes them. They are still removed only after the verification and the migration; a failed deploy removes nothing. remove_replaced_images.sh says nothing about an image still in use, which most of them now are on every deploy, and names only what it removed or could not remove.
144 lines
5.6 KiB
Python
144 lines
5.6 KiB
Python
"""A deploy removes the images it replaced, and nothing else (NetOrk/kb-server#157).
|
|
|
|
It ended with `docker image prune -af`: every image no container used at that
|
|
moment, on a host that may run other things too. Now it records the images of
|
|
netOrk's containers before the first of them can be replaced, and, once the swap
|
|
is verified and the migration ran, hands them to remote/remove_replaced_images.sh.
|
|
|
|
"netOrk's containers" are every container of the compose project `netork`: the
|
|
engine, and also the bundled database (behind its compose profile), the broker,
|
|
the infrastructure containers and a retired service such as the old registry.
|
|
The database step and the broker step replace their containers before the
|
|
engine's swap, so the record is taken before the database step.
|
|
|
|
The remote side is a fake `ssh` that records every command and plays a host whose
|
|
netOrk containers run one image.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
DEPLOY = Path(__file__).resolve().parent.parent / "deploy.sh"
|
|
|
|
OLD = "sha256:" + "0" * 64
|
|
|
|
_FAKE_SSH = """#!/bin/sh
|
|
for arg in "$@"; do cmd="$arg"; done
|
|
case "$cmd" in *.deploy.lock*) exec sh -c "$cmd" ;; esac
|
|
case "$cmd" in
|
|
*"bash -s"*) cat > "{state}/stdin-$(date +%s%N)" ;;
|
|
*) cat > /dev/null ;;
|
|
esac
|
|
printf '%s\\n----\\n' "$cmd" >> "{state}/commands"
|
|
case "$cmd" in
|
|
*"xargs -r docker inspect"*) printf '{recorded}' ;;
|
|
*"alembic upgrade head"*) exit {migrate_exit} ;;
|
|
esac
|
|
exit 0
|
|
"""
|
|
|
|
|
|
def _deploy(
|
|
tmp_path: Path, *, recorded: str = f"{OLD}\n", migrate_exit: int = 0
|
|
) -> tuple[subprocess.CompletedProcess[str], list[str]]:
|
|
bin_dir = tmp_path / "bin"
|
|
bin_dir.mkdir()
|
|
fake = bin_dir / "ssh"
|
|
fake.write_text(
|
|
_FAKE_SSH.replace("{state}", str(tmp_path))
|
|
.replace("{recorded}", recorded.replace("\n", "\\n"))
|
|
.replace("{migrate_exit}", str(migrate_exit))
|
|
)
|
|
fake.chmod(0o755)
|
|
result = subprocess.run(
|
|
["bash", str(DEPLOY), "testhost"],
|
|
env={
|
|
"PATH": f"{bin_dir}:{os.environ['PATH']}",
|
|
"HOME": str(tmp_path),
|
|
"DEPLOY_ENV_FILE": "/dev/null",
|
|
"REGISTRY_HOST": "registry.example",
|
|
"NETORK_VERSION": "latest-dev",
|
|
},
|
|
stdin=subprocess.DEVNULL,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=60,
|
|
check=False,
|
|
)
|
|
commands = (tmp_path / "commands").read_text().split("\n----\n")
|
|
return result, commands
|
|
|
|
|
|
def _index(commands: list[str], needle: str) -> int:
|
|
return next(i for i, cmd in enumerate(commands) if needle in cmd)
|
|
|
|
|
|
def _removals(commands: list[str]) -> list[str]:
|
|
return [cmd for cmd in commands if "bash -s -- sha256:" in cmd]
|
|
|
|
|
|
def test_no_prune_of_everything(tmp_path: Path) -> None:
|
|
result, commands = _deploy(tmp_path)
|
|
assert result.returncode == 0, result.stderr
|
|
assert not [cmd for cmd in commands if "image prune" in cmd]
|
|
|
|
|
|
def test_the_replaced_images_are_recorded_before_any_container_is_replaced(
|
|
tmp_path: Path,
|
|
) -> None:
|
|
result, commands = _deploy(tmp_path)
|
|
assert result.returncode == 0, result.stderr
|
|
recorded = _index(commands, "xargs -r docker inspect")
|
|
assert recorded > _index(commands, "pull netork-api")
|
|
assert recorded < _index(commands, "bash -s -- reconcile") # the database step
|
|
assert recorded < _index(commands, "--wait-timeout 120 redis") # the broker
|
|
assert recorded < _index(commands, "--force-recreate") # the engine
|
|
|
|
|
|
def test_the_record_covers_every_container_of_the_project(tmp_path: Path) -> None:
|
|
"""Not only the engine services: postgres sits behind a compose profile, and the
|
|
retired registry is in no compose file any more, so `compose ps` misses both."""
|
|
_, commands = _deploy(tmp_path)
|
|
record = commands[_index(commands, "xargs -r docker inspect")]
|
|
assert "docker ps -aq --filter label=com.docker.compose.project=netork" in record
|
|
assert "compose" not in record.replace("com.docker.compose.project", "")
|
|
|
|
|
|
def test_they_are_removed_after_the_migration_through_the_script(tmp_path: Path) -> None:
|
|
result, commands = _deploy(tmp_path)
|
|
assert result.returncode == 0, result.stderr
|
|
(removal,) = _removals(commands)
|
|
assert removal.strip() == f"bash -s -- {OLD}"
|
|
verified = _index(commands, "docker image inspect --format '{{.Id}}'")
|
|
assert verified < _index(commands, "alembic upgrade head") < commands.index(removal)
|
|
sent = [p.read_text() for p in tmp_path.glob("stdin-*")]
|
|
assert any("remove_replaced_images.sh" in text for text in sent), result.stdout
|
|
|
|
|
|
def test_a_failed_deploy_removes_nothing(tmp_path: Path) -> None:
|
|
"""The old images are the way back until the deploy went through."""
|
|
result, commands = _deploy(tmp_path, migrate_exit=1)
|
|
assert result.returncode != 0
|
|
assert not _removals(commands)
|
|
|
|
|
|
def test_nothing_recorded_means_no_removal(tmp_path: Path) -> None:
|
|
"""A first deploy: no containers yet, nothing replaced."""
|
|
result, commands = _deploy(tmp_path, recorded="")
|
|
assert result.returncode == 0, result.stderr
|
|
assert not _removals(commands)
|
|
assert "Removing the images" not in result.stdout
|
|
|
|
|
|
def test_only_image_ids_reach_the_remote_command_line(tmp_path: Path) -> None:
|
|
"""The IDs are expanded into the ssh command; anything else the host printed
|
|
(a login script's greeting, say) is not passed on as an image to remove."""
|
|
new = "sha256:" + "a" * 64
|
|
result, commands = _deploy(tmp_path, recorded=f"Welcome; rm -rf ~\npostgres\n{OLD}\n{new}\n")
|
|
assert result.returncode == 0, result.stderr
|
|
(removal,) = _removals(commands)
|
|
assert removal.strip() == f"bash -s -- {OLD} {new}"
|