|
| 1 | +"""Plan or remove old, reproducible DEV API images; never prune Docker globally.""" |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +import os |
| 6 | +import re |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +from datetime import datetime, timedelta, timezone |
| 10 | + |
| 11 | +TAG = re.compile(r"procollab-dev-api:([0-9a-f]{40})(?:-[0-9a-f]{12})?$") |
| 12 | +REPO = "/root/api" |
| 13 | + |
| 14 | + |
| 15 | +def command(*args): |
| 16 | + return subprocess.check_output(args, text=True).strip() |
| 17 | + |
| 18 | + |
| 19 | +def require(condition, message): |
| 20 | + if not condition: |
| 21 | + raise RuntimeError(message) |
| 22 | + |
| 23 | + |
| 24 | +def output(message): |
| 25 | + sys.stdout.write(message + "\n") |
| 26 | + sys.stdout.flush() |
| 27 | + |
| 28 | + |
| 29 | +def digest(value): |
| 30 | + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() |
| 31 | + |
| 32 | + |
| 33 | +def inventory(): |
| 34 | + result = {} |
| 35 | + for image_id in set(command("docker", "image", "ls", "-aq", "--no-trunc").split()): |
| 36 | + value = json.loads( |
| 37 | + command( |
| 38 | + "docker", |
| 39 | + "image", |
| 40 | + "inspect", |
| 41 | + "--format", |
| 42 | + '{"id":{{json .Id}},"tags":{{json .RepoTags}},"created":{{json .Created}}}', |
| 43 | + image_id, |
| 44 | + ) |
| 45 | + ) |
| 46 | + value["tags"] = sorted(value["tags"] or []) |
| 47 | + result[image_id] = value |
| 48 | + return result |
| 49 | + |
| 50 | + |
| 51 | +def containers(): |
| 52 | + result = [] |
| 53 | + for container_id in command("docker", "ps", "-aq", "--no-trunc").split(): |
| 54 | + result.append( |
| 55 | + json.loads( |
| 56 | + command( |
| 57 | + "docker", |
| 58 | + "inspect", |
| 59 | + "--format", |
| 60 | + '{"id":{{json .Id}},"image":{{json .Image}},"state":{{json .State.Status}},' |
| 61 | + '"started":{{json .State.StartedAt}},"restarts":{{json .RestartCount}}}', |
| 62 | + container_id, |
| 63 | + ) |
| 64 | + ) |
| 65 | + ) |
| 66 | + return sorted(result, key=lambda value: value["id"]) |
| 67 | + |
| 68 | + |
| 69 | +def volumes(): |
| 70 | + return sorted( |
| 71 | + command( |
| 72 | + "docker", "volume", "ls", "--format", "{{.Driver}} {{.Name}}" |
| 73 | + ).splitlines() |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +def created_at(image): |
| 78 | + value = re.sub(r"(\.\d{6})\d+", r"\1", image["created"]) |
| 79 | + return datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 80 | + |
| 81 | + |
| 82 | +def plan(images, container_rows, volume_rows, now, reachable): |
| 83 | + used = {row["image"] for row in container_rows} |
| 84 | + reproducible = [] |
| 85 | + for image in images.values(): |
| 86 | + tags = image["tags"] |
| 87 | + matches = [TAG.fullmatch(tag) for tag in tags] |
| 88 | + if tags and all(matches) and all(reachable(match[1]) for match in matches): |
| 89 | + reproducible.append(image) |
| 90 | + newest = { |
| 91 | + image["id"] |
| 92 | + for image in sorted( |
| 93 | + reproducible, key=lambda row: (created_at(row), row["id"]), reverse=True |
| 94 | + )[:3] |
| 95 | + } |
| 96 | + candidates = sorted( |
| 97 | + ( |
| 98 | + image |
| 99 | + for image in reproducible |
| 100 | + if image["id"] not in used | newest |
| 101 | + and created_at(image) < now - timedelta(hours=48) |
| 102 | + ), |
| 103 | + key=lambda image: image["id"], |
| 104 | + ) |
| 105 | + proof = { |
| 106 | + "images": images, |
| 107 | + "containers": container_rows, |
| 108 | + "volumes": volume_rows, |
| 109 | + "candidates": candidates, |
| 110 | + } |
| 111 | + return { |
| 112 | + "sha256": digest(proof), |
| 113 | + "candidates": candidates, |
| 114 | + "protected_count": len(images) - len(candidates), |
| 115 | + } |
| 116 | + |
| 117 | + |
| 118 | +def apply(plan_value, expected, images_before, containers_before, volumes_before): |
| 119 | + if plan_value["sha256"] != expected: |
| 120 | + raise RuntimeError("Image inventory changed; inspect a new plan before cleanup") |
| 121 | + remaining = dict(images_before) |
| 122 | + for image in plan_value["candidates"]: |
| 123 | + if ( |
| 124 | + containers() != containers_before |
| 125 | + or volumes() != volumes_before |
| 126 | + or inventory() != remaining |
| 127 | + ): |
| 128 | + raise RuntimeError("Docker state changed; no further images will be removed") |
| 129 | + for tag in image["tags"]: |
| 130 | + # Non-force removal preserves images referenced by any container. |
| 131 | + # --no-prune also prevents removal of untagged parent images. |
| 132 | + subprocess.run(["docker", "image", "rm", "--no-prune", tag], check=True) |
| 133 | + del remaining[image["id"]] |
| 134 | + if ( |
| 135 | + inventory() != remaining |
| 136 | + or containers() != containers_before |
| 137 | + or volumes() != volumes_before |
| 138 | + ): |
| 139 | + raise RuntimeError("Docker state differs from the reviewed removal plan") |
| 140 | + output( |
| 141 | + "PROTECTED_IMAGES_UNCHANGED=true\nCONTAINERS_UNCHANGED=true\nVOLUMES_UNCHANGED=true" |
| 142 | + ) |
| 143 | + |
| 144 | + |
| 145 | +def main(): |
| 146 | + mode, expected = sys.argv[1:] |
| 147 | + require(mode in ("plan", "apply"), "Invalid operation") |
| 148 | + require( |
| 149 | + mode == "plan" or re.fullmatch(r"[0-9a-f]{64}", expected), "Inspect a plan first" |
| 150 | + ) |
| 151 | + require( |
| 152 | + os.geteuid() == 0 and os.path.realpath(REPO) == REPO, |
| 153 | + "Unexpected host or repository", |
| 154 | + ) |
| 155 | + command( |
| 156 | + "git", |
| 157 | + "-C", |
| 158 | + REPO, |
| 159 | + "merge-base", |
| 160 | + "--is-ancestor", |
| 161 | + "beef71645567128398d0afa5a2eb80dc6bc8dac7", |
| 162 | + "HEAD", |
| 163 | + ) |
| 164 | + command( |
| 165 | + "grep", |
| 166 | + "-Eq", |
| 167 | + r"server_name[[:space:]]+dev\.procollab\.ru;", |
| 168 | + "/etc/nginx/sites-enabled/dev.procollab.ru", |
| 169 | + ) |
| 170 | + runtime = [] |
| 171 | + for service in ("web", "celerys"): |
| 172 | + container_id = command( |
| 173 | + "docker", |
| 174 | + "ps", |
| 175 | + "-q", |
| 176 | + "--no-trunc", |
| 177 | + "--filter", |
| 178 | + f"label=com.docker.compose.project.working_dir={REPO}", |
| 179 | + "--filter", |
| 180 | + f"label=com.docker.compose.service={service}", |
| 181 | + ) |
| 182 | + require( |
| 183 | + re.fullmatch(r"[0-9a-f]{64}", container_id), |
| 184 | + "Expected one running DEV service", |
| 185 | + ) |
| 186 | + reference = command("docker", "inspect", "-f", "{{.Config.Image}}", container_id) |
| 187 | + require(TAG.fullmatch(reference), "Unexpected DEV image reference") |
| 188 | + runtime.append(command("docker", "inspect", "-f", "{{.Image}}", container_id)) |
| 189 | + require(len(set(runtime)) == 1, "DEV web and worker image mismatch") |
| 190 | + images_before, containers_before, volumes_before = ( |
| 191 | + inventory(), |
| 192 | + containers(), |
| 193 | + volumes(), |
| 194 | + ) |
| 195 | + |
| 196 | + def reachable(sha): |
| 197 | + return ( |
| 198 | + subprocess.run( |
| 199 | + ["git", "-C", REPO, "merge-base", "--is-ancestor", sha, "HEAD"], |
| 200 | + stdout=subprocess.DEVNULL, |
| 201 | + stderr=subprocess.DEVNULL, |
| 202 | + ).returncode |
| 203 | + == 0 |
| 204 | + ) |
| 205 | + |
| 206 | + value = plan( |
| 207 | + images_before, |
| 208 | + containers_before, |
| 209 | + volumes_before, |
| 210 | + datetime.now(timezone.utc), |
| 211 | + reachable, |
| 212 | + ) |
| 213 | + output("DEV_IMAGE_RETENTION_PLAN=" + json.dumps(value, sort_keys=True)) |
| 214 | + output(command("df", "-h", "/")) |
| 215 | + if mode == "apply": |
| 216 | + apply(value, expected, images_before, containers_before, volumes_before) |
| 217 | + output(command("df", "-h", "/")) |
| 218 | + |
| 219 | + |
| 220 | +if __name__ == "__main__": |
| 221 | + main() |
0 commit comments