2026-11-30 22:50:15 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import io
|
|
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
import subprocess
|
|
|
|
|
import time
|
|
|
|
|
from contextlib import redirect_stderr, redirect_stdout
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
from unittest.mock import patch
|
|
|
|
|
|
|
|
|
|
from pkgmgr.actions.branch import gc
|
|
|
|
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
|
|
|
|
from pkgmgr.actions.gc.risk import docker_items, plan
|
2026-12-01 11:04:07 +00:00
|
|
|
from tests.support.git_sandbox import git, isolated_root, origin_and_repo
|
2026-11-30 22:50:15 +00:00
|
|
|
|
|
|
|
|
DAY = 86400
|
|
|
|
|
REAL_RUN = subprocess.run
|
|
|
|
|
DANGLING_ID = "sha256:" + "d" * 64
|
|
|
|
|
TAGGED_ID = "sha256:" + "a" * 64
|
|
|
|
|
USED_ID = "sha256:" + "u" * 64
|
|
|
|
|
OLD_CACHE = "oldcache0000000000000000a"
|
|
|
|
|
NEW_CACHE = "newcache0000000000000000b"
|
|
|
|
|
BUSY_CACHE = "busycache000000000000000c"
|
|
|
|
|
BARE_CONTAINER = "c" * 64
|
|
|
|
|
VOLUME_CONTAINER = "v" * 64
|
|
|
|
|
RUNNING_CONTAINER = "r" * 64
|
|
|
|
|
IMAGES = (
|
|
|
|
|
(DANGLING_ID, "0", "<none>", "<none>", "1.5GB"),
|
|
|
|
|
(TAGGED_ID, "0", "app", "old", "200MB"),
|
|
|
|
|
(USED_ID, "2", "app", "live", "300MB"),
|
|
|
|
|
)
|
|
|
|
|
CACHES = (
|
|
|
|
|
(OLD_CACHE, "false", "265MB", 8, "8 days ago"),
|
|
|
|
|
(NEW_CACHE, "false", "10kB", 2, "2 days ago"),
|
|
|
|
|
(BUSY_CACHE, "true", "1GB", 30, "4 weeks ago"),
|
|
|
|
|
)
|
|
|
|
|
CONTAINERS = (
|
|
|
|
|
(
|
|
|
|
|
BARE_CONTAINER,
|
|
|
|
|
"exited",
|
|
|
|
|
"0",
|
|
|
|
|
"bare",
|
|
|
|
|
"Exited (0)",
|
|
|
|
|
"com.docker.compose.project=demo,x=y",
|
|
|
|
|
),
|
|
|
|
|
(VOLUME_CONTAINER, "exited", "1", "withvol", "Exited (1)", ""),
|
|
|
|
|
(RUNNING_CONTAINER, "running", "0", "live", "Up", ""),
|
|
|
|
|
)
|
|
|
|
|
VOLUMES = [
|
|
|
|
|
{
|
|
|
|
|
"Name": "demo_data",
|
|
|
|
|
"Links": "0",
|
|
|
|
|
"Size": "2GB",
|
|
|
|
|
"Labels": "com.docker.compose.project=demo",
|
|
|
|
|
},
|
|
|
|
|
{"Name": "live_data", "Links": "1", "Size": "1GB", "Labels": ""},
|
|
|
|
|
]
|
|
|
|
|
OWNERS = {
|
|
|
|
|
"old-done.log": "done",
|
|
|
|
|
"old-stopped": "Stopped",
|
|
|
|
|
"new-done.log": "done",
|
|
|
|
|
"old-running.log": "running",
|
|
|
|
|
"checkout": "done",
|
|
|
|
|
}
|
|
|
|
|
SCRATCH_FILES = ("old-done.log", "new-done.log", "old-running.log", "old-unknown.log")
|
|
|
|
|
OLD_SCRATCH = ("old-done.log", "old-stopped", "old-running.log", "old-unknown.log")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stamp(epoch: float) -> str:
|
|
|
|
|
moment = datetime.fromtimestamp(epoch, tz=timezone.utc)
|
|
|
|
|
return moment.strftime("%Y-%m-%d %H:%M:%S.%f") + "123 +0000 UTC"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def docker_df(now: float) -> dict:
|
|
|
|
|
return {
|
|
|
|
|
"Images": [
|
|
|
|
|
{
|
|
|
|
|
"ID": image_id,
|
|
|
|
|
"Containers": containers,
|
|
|
|
|
"Repository": repository,
|
|
|
|
|
"Tag": tag,
|
|
|
|
|
"UniqueSize": size,
|
|
|
|
|
"CreatedAt": stamp(now),
|
|
|
|
|
}
|
|
|
|
|
for image_id, containers, repository, tag, size in IMAGES
|
|
|
|
|
],
|
|
|
|
|
"BuildCache": [
|
|
|
|
|
{
|
|
|
|
|
"ID": cache_id,
|
|
|
|
|
"InUse": in_use,
|
|
|
|
|
"Size": size,
|
|
|
|
|
"LastUsedAt": stamp(now - days * DAY),
|
|
|
|
|
"LastUsedSince": since,
|
|
|
|
|
}
|
|
|
|
|
for cache_id, in_use, size, days, since in CACHES
|
|
|
|
|
],
|
|
|
|
|
"Containers": [
|
|
|
|
|
{
|
|
|
|
|
"ID": container_id,
|
|
|
|
|
"State": state,
|
|
|
|
|
"LocalVolumes": volumes,
|
|
|
|
|
"Names": names,
|
|
|
|
|
"Image": "app:live",
|
|
|
|
|
"Status": status,
|
|
|
|
|
"Labels": labels,
|
|
|
|
|
}
|
|
|
|
|
for container_id, state, volumes, names, status, labels in CONTAINERS
|
|
|
|
|
],
|
|
|
|
|
"Volumes": VOLUMES,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class FakeDocker:
|
|
|
|
|
def __init__(self, now: float) -> None:
|
|
|
|
|
self.calls: list[list[str]] = []
|
|
|
|
|
self.df = json.dumps(docker_df(now))
|
|
|
|
|
|
|
|
|
|
def __call__(self, args: list[str]) -> str:
|
|
|
|
|
self.calls.append(list(args))
|
|
|
|
|
if args == docker_items.DF_VERBOSE:
|
|
|
|
|
return self.df
|
|
|
|
|
if args == docker_items.DANGLING:
|
|
|
|
|
return DANGLING_ID + "\n"
|
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
def writes(self) -> list[list[str]]:
|
|
|
|
|
reads = (docker_items.DF_VERBOSE, docker_items.DANGLING)
|
|
|
|
|
return [call for call in self.calls if call not in reads]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def inside(path: str, root: str) -> bool:
|
|
|
|
|
return path == root or path.startswith(root + os.sep)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write(path: str, text: str) -> None:
|
|
|
|
|
with open(path, "w") as fh:
|
|
|
|
|
fh.write(text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RiskPlanFixture:
|
|
|
|
|
def setUp(self) -> None:
|
|
|
|
|
self.root = isolated_root(self, {"GIT_ALLOW_PROTOCOL": "file"})
|
|
|
|
|
self.commands: list[list[str]] = []
|
|
|
|
|
self._start(patch("subprocess.run", self._guarded_run))
|
|
|
|
|
self._repos()
|
|
|
|
|
self._scratch()
|
|
|
|
|
self.now = time.time()
|
|
|
|
|
self.docker = FakeDocker(self.now)
|
|
|
|
|
self.forge = ForgeFacts()
|
|
|
|
|
self.containers = [gc.Container("stackproj", self.wt["stack"], "img")]
|
|
|
|
|
self.host_ns = True
|
|
|
|
|
self.include: list[str] = []
|
|
|
|
|
|
|
|
|
|
def _start(self, patcher) -> None:
|
|
|
|
|
patcher.start()
|
|
|
|
|
self.addCleanup(patcher.stop)
|
|
|
|
|
|
|
|
|
|
def _guarded_run(self, cmd, *args, **kwargs):
|
|
|
|
|
argv = [str(part) for part in cmd]
|
|
|
|
|
self.commands.append(argv)
|
|
|
|
|
if os.path.basename(argv[0]) not in ("git", "du"):
|
|
|
|
|
raise AssertionError(f"unexpected command outside the mocks: {argv}")
|
|
|
|
|
cwd = os.path.realpath(kwargs.get("cwd") or os.getcwd())
|
|
|
|
|
for path in [cwd, *(a for a in argv[1:] if a.startswith("/"))]:
|
|
|
|
|
if not inside(os.path.realpath(path), self.root):
|
|
|
|
|
raise AssertionError(f"{argv} reaches {path} outside {self.root}")
|
|
|
|
|
return REAL_RUN(cmd, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
def _commit(self, cwd: str, name: str) -> None:
|
|
|
|
|
write(os.path.join(cwd, f"{name}.txt"), name)
|
|
|
|
|
git(cwd, "add", f"{name}.txt")
|
|
|
|
|
git(cwd, "commit", "-m", name)
|
|
|
|
|
|
|
|
|
|
def _branch(self, name: str, *, push: bool, merge: bool = False) -> None:
|
|
|
|
|
git(self.repo, "checkout", "-b", name, "main")
|
|
|
|
|
self._commit(self.repo, name)
|
|
|
|
|
if push:
|
|
|
|
|
git(self.repo, "push", "origin", name)
|
|
|
|
|
git(self.repo, "checkout", "main")
|
|
|
|
|
if merge:
|
|
|
|
|
git(self.repo, "merge", "--no-ff", "-m", f"merge {name}", name)
|
|
|
|
|
git(self.repo, "push", "origin", "main")
|
|
|
|
|
|
|
|
|
|
def _repos(self) -> None:
|
2026-12-01 11:04:07 +00:00
|
|
|
self.origin, self.repo = origin_and_repo(self.root)
|
2026-11-30 22:50:15 +00:00
|
|
|
self._branch("cherry", push=False)
|
|
|
|
|
for name in ("done", "stack", "old"):
|
|
|
|
|
self._branch(name, push=True, merge=True)
|
|
|
|
|
git(self.repo, "branch", "dirty", "done")
|
|
|
|
|
self._branch("pushed", push=True)
|
|
|
|
|
self._branch("wip", push=False)
|
|
|
|
|
git(self.repo, "cherry-pick", "cherry")
|
|
|
|
|
git(self.repo, "push", "origin", "main")
|
|
|
|
|
git(self.repo, "remote", "set-head", "origin", "main")
|
|
|
|
|
self.wt = {}
|
|
|
|
|
for name in ("done", "dirty", "stack", "pushed", "wip", "cherry"):
|
|
|
|
|
self.wt[name] = os.path.join(self.root, f"wt-{name}")
|
|
|
|
|
git(self.repo, "worktree", "add", self.wt[name], name)
|
|
|
|
|
write(os.path.join(self.wt["dirty"], "untracked.txt"), "x")
|
|
|
|
|
|
|
|
|
|
def _old(self, path: str) -> None:
|
|
|
|
|
old = time.time() - 2 * DAY
|
|
|
|
|
for base, dirs, files in os.walk(path):
|
|
|
|
|
for name in [*dirs, *files]:
|
|
|
|
|
os.utime(os.path.join(base, name), (old, old))
|
|
|
|
|
os.utime(path, (old, old))
|
|
|
|
|
|
|
|
|
|
def _scratch(self) -> None:
|
|
|
|
|
self.tmp = os.path.join(self.root, "scratch")
|
|
|
|
|
os.makedirs(self.tmp)
|
|
|
|
|
self.t = {
|
|
|
|
|
name: os.path.join(self.tmp, name)
|
|
|
|
|
for name in (*SCRATCH_FILES, "old-stopped", "checkout")
|
|
|
|
|
}
|
|
|
|
|
for name in SCRATCH_FILES:
|
|
|
|
|
write(self.t[name], name)
|
|
|
|
|
os.makedirs(os.path.join(self.t["old-stopped"], "deep"))
|
|
|
|
|
write(os.path.join(self.t["old-stopped"], "deep", "x.log"), "x")
|
|
|
|
|
os.makedirs(self.t["checkout"])
|
|
|
|
|
write(os.path.join(self.t["checkout"], ".git"), "gitdir: /nowhere\n")
|
|
|
|
|
for name in (*OLD_SCRATCH, "checkout"):
|
|
|
|
|
self._old(self.t[name])
|
|
|
|
|
os.symlink(self.t["old-done.log"], os.path.join(self.tmp, "link"))
|
|
|
|
|
self.owners = os.path.join(self.root, "owners.json")
|
|
|
|
|
with open(self.owners, "w") as fh:
|
|
|
|
|
json.dump({self.t[name]: status for name, status in OWNERS.items()}, fh)
|
|
|
|
|
|
|
|
|
|
def request(self, level: str, apply: bool) -> plan.RiskRequest:
|
|
|
|
|
return plan.RiskRequest(
|
|
|
|
|
level=level,
|
|
|
|
|
apply=apply,
|
|
|
|
|
as_json=True,
|
|
|
|
|
owners_file=self.owners,
|
|
|
|
|
include=self.include,
|
|
|
|
|
exclude=[],
|
|
|
|
|
merged_into=[],
|
|
|
|
|
sizes=False,
|
|
|
|
|
min_age=None,
|
|
|
|
|
hooks={},
|
|
|
|
|
tmp_root=self.tmp,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def run_gc(self, level: str, apply: bool = False) -> tuple[int, dict, str]:
|
|
|
|
|
out, err = io.StringIO(), io.StringIO()
|
|
|
|
|
no_gc_docker = AssertionError("gc must not call docker for low items")
|
|
|
|
|
with (
|
|
|
|
|
patch.object(gc, "host_pid_namespace", return_value=self.host_ns),
|
|
|
|
|
patch.object(plan, "host_pid_namespace", return_value=self.host_ns),
|
|
|
|
|
patch.object(gc, "_process_cwds", return_value={}),
|
|
|
|
|
patch.object(plan, "_process_cwds", return_value={}),
|
|
|
|
|
patch.object(gc, "list_compose_containers", return_value=self.containers),
|
|
|
|
|
patch.object(gc, "fetch_forge_facts", return_value=self.forge),
|
|
|
|
|
patch.object(gc, "_docker", side_effect=no_gc_docker),
|
|
|
|
|
patch.object(docker_items, "_docker", side_effect=self.docker),
|
|
|
|
|
redirect_stdout(out),
|
|
|
|
|
redirect_stderr(err),
|
|
|
|
|
):
|
|
|
|
|
code = plan.risk_cleanup([self.repo], self.request(level, apply))
|
|
|
|
|
printed = json.loads(out.getvalue()) if out.getvalue().strip() else {}
|
|
|
|
|
return code, printed, err.getvalue()
|
|
|
|
|
|
|
|
|
|
def risks(self, printed: dict) -> dict[str, str]:
|
|
|
|
|
return {entry["name"]: entry["risk"] for entry in printed["items"]}
|
|
|
|
|
|
|
|
|
|
def entry(self, printed: dict, name: str) -> dict:
|
|
|
|
|
return next(e for e in printed["items"] if e["name"] == name)
|
|
|
|
|
|
|
|
|
|
def refs(self, cwd: str) -> str:
|
|
|
|
|
return git(cwd, "for-each-ref", "--format=%(refname) %(objectname)")
|