-
Notifications
You must be signed in to change notification settings - Fork 2
262 lines (235 loc) · 10.7 KB
/
Copy pathcleanup.yml
File metadata and controls
262 lines (235 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
name: Cleanup old artifacts and GHCR images
on:
schedule:
- cron: '00 3 * * *'
workflow_dispatch:
inputs:
dry_run:
description: "List what would be deleted, without deleting it"
required: false
default: "false"
type: choice
options:
- "false"
- "true"
permissions:
contents: read
env:
ARTIFACT_RETENTION_DAYS: 14
# Stale tagged versions still have tags, but those tags are no longer generated by the current image matrix.
STALE_TAGGED_RETENTION_DAYS: 14
# Untagged versions are usually platform/attestation child manifests of a multi-arch OCI index. We keep any
# child still referenced by a live tag; an unreferenced (orphaned) child is deleted once it is older than
# this grace window. The grace avoids racing an in-progress multi-arch push whose index manifest, and thus
# the link to its children, is not yet readable.
UNTAGGED_ORPHAN_GRACE_DAYS: 3
jobs:
artifacts:
name: old artifact cleanup
runs-on: ubuntu-latest
permissions:
actions: write
contents: read
steps:
- name: Cleanup workflow artifacts
uses: actions/github-script@v8
env:
DRY_RUN: ${{ inputs.dry_run || 'false' }}
ARTIFACT_RETENTION_DAYS: ${{ env.ARTIFACT_RETENTION_DAYS }}
with:
script: |
const dryRun = process.env.DRY_RUN === 'true';
const retentionMs = Number(process.env.ARTIFACT_RETENTION_DAYS) * 24 * 60 * 60 * 1000;
const cutoff = Date.now() - retentionMs;
const artifacts = await github.paginate(github.rest.actions.listArtifactsForRepo, {
owner: context.repo.owner,
repo: context.repo.repo,
per_page: 100,
});
let deleted = 0;
for (const artifact of artifacts) {
const createdAt = new Date(artifact.created_at).getTime();
if (createdAt >= cutoff) {
core.info(`keep ${artifact.name}: created ${artifact.created_at}`);
continue;
}
core.info(`${dryRun ? 'would delete' : 'delete'} ${artifact.name}: created ${artifact.created_at}`);
if (!dryRun) {
await github.rest.actions.deleteArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: artifact.id,
});
}
deleted += 1;
}
core.notice(`${dryRun ? 'Would delete' : 'Deleted'} ${deleted} artifact(s).`);
ghcr:
name: ghcr.io cleanup
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # needed for deletions with GITHUB_TOKEN
steps:
- name: Checkout repository
uses: actions/checkout@v6
- id: keep-tags
name: Compute current image tags
shell: bash
run: |
set -euo pipefail
source ci/tags_config.sh
tags=()
images=()
for gemc_tag in $(get_gemc_tags); do
for pair in "${OS_VERSIONS[@]}"; do
os="${pair%%=*}"
ver="${pair#*=}"
images+=("$os")
base="${gemc_tag}-${os}-${ver}"
tags+=("$base" "$base-amd64")
if [[ "$os" != "archlinux" ]]; then
tags+=("$base-arm64")
fi
done
done
for arch in $(get_cpu_architectures); do
tags+=("cache-$arch")
done
{
echo "json<<EOF"
printf '%s\n' "${tags[@]}" | jq -R -s -c 'split("\n")[:-1] | unique'
echo "EOF"
echo "images<<EOF"
printf '%s\n' "${images[@]}" | jq -R -s -c 'split("\n")[:-1] | unique'
echo "EOF"
} >> "$GITHUB_OUTPUT"
- id: referenced-digests
name: Collect child digests referenced by current tags
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
repo="${GITHUB_REPOSITORY,,}" # owner/repo, lowercased for the registry path
registry="https://ghcr.io"
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"
token="$(curl -fsSL -u "${GITHUB_ACTOR}:${GITHUB_TOKEN}" \
"${registry}/token?service=ghcr.io&scope=repository:${repo}:pull" | jq -r '.token')"
tags="$(curl -fsSL -H "Authorization: Bearer ${token}" \
"${registry}/v2/${repo}/tags/list?n=10000" | jq -r '.tags[]?')"
: > referenced-digests.txt
# Every tag present in the registry is an image index (multi-arch) or a single image. For indexes,
# record the digests of the per-platform / attestation child manifests they reference, so the cleanup
# step never deletes a child a live tag still points to. Fail closed: any fetch error aborts the job
# via 'set -e' before anything is deleted, rather than risk treating a referenced child as orphaned.
for tag in ${tags}; do
curl -fsSL -H "Authorization: Bearer ${token}" -H "Accept: ${accept}" \
"${registry}/v2/${repo}/manifests/${tag}" \
| jq -r 'try .manifests[].digest' >> referenced-digests.txt
done
sort -u -o referenced-digests.txt referenced-digests.txt
echo "Collected $(wc -l < referenced-digests.txt) referenced child digest(s) from $(echo "${tags}" | wc -w) tag(s)."
- name: Cleanup GHCR package versions
uses: actions/github-script@v8
env:
KEEP_TAGS: ${{ steps.keep-tags.outputs.json }}
MANAGED_IMAGES: ${{ steps.keep-tags.outputs.images }}
DRY_RUN: ${{ inputs.dry_run || 'false' }}
STALE_TAGGED_RETENTION_DAYS: ${{ env.STALE_TAGGED_RETENTION_DAYS }}
UNTAGGED_ORPHAN_GRACE_DAYS: ${{ env.UNTAGGED_ORPHAN_GRACE_DAYS }}
with:
script: |
const keepTags = new Set(JSON.parse(process.env.KEEP_TAGS));
const managedImages = JSON.parse(process.env.MANAGED_IMAGES);
const dryRun = process.env.DRY_RUN === 'true';
const staleTaggedRetentionMs =
Number(process.env.STALE_TAGGED_RETENTION_DAYS) * 24 * 60 * 60 * 1000;
const untaggedOrphanGraceMs =
Number(process.env.UNTAGGED_ORPHAN_GRACE_DAYS) * 24 * 60 * 60 * 1000;
const now = Date.now();
const fs = require('fs');
let referencedDigests;
try {
referencedDigests = new Set(
fs.readFileSync('referenced-digests.txt', 'utf8')
.split('\n').map((line) => line.trim()).filter(Boolean)
);
} catch (error) {
core.setFailed(`Unable to read referenced-digests.txt: ${error.message}`);
return;
}
core.info(`Loaded ${referencedDigests.size} digest(s) referenced by live tags.`);
const owner = context.repo.owner;
const packageName = context.repo.repo.toLowerCase();
const ownerType = context.payload.repository.owner.type;
const isOrg = ownerType === 'Organization';
const listVersions = isOrg
? github.rest.packages.getAllPackageVersionsForPackageOwnedByOrg
: github.rest.packages.getAllPackageVersionsForPackageOwnedByUser;
const deleteVersion = isOrg
? github.rest.packages.deletePackageVersionForOrg
: github.rest.packages.deletePackageVersionForUser;
const ownerArgs = isOrg ? { org: owner } : { username: owner };
const packageArgs = {
...ownerArgs,
package_type: 'container',
package_name: packageName,
per_page: 100,
};
const versions = await github.paginate(listVersions, packageArgs);
const cacheTag = /^cache-[a-z0-9_-]+$/;
const escapedImages = managedImages
.map((image) => image.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|');
const managedTag = new RegExp(`^.+-(${escapedImages})-[a-z0-9.]+(-(amd64|arm64))?$`);
core.info(`Keeping current tags: ${[...keepTags].sort().join(', ')}`);
core.info(`Managed image families: ${managedImages.sort().join(', ')}`);
core.info(`Found ${versions.length} package versions in ghcr.io/${owner}/${packageName}`);
let deleted = 0;
for (const version of versions) {
const tags = version.metadata?.container?.tags ?? [];
const createdAt = new Date(version.created_at).getTime();
const updatedAt = new Date(version.updated_at).getTime();
const ageMs = now - createdAt;
const tagList = tags.length ? tags.join(', ') : '<untagged>';
const dates = `created ${version.created_at}, updated ${version.updated_at}`;
let reason = null;
if (tags.length === 0) {
if (referencedDigests.has(version.name)) {
core.info(`keep ${version.id}: ${tagList} ${version.name} (${dates}; referenced by a live tag)`);
continue;
}
if (ageMs < untaggedOrphanGraceMs) {
core.info(
`keep ${version.id}: ${tagList} ${version.name} (${dates}; orphaned but within ` +
`${process.env.UNTAGGED_ORPHAN_GRACE_DAYS}-day grace)`
);
continue;
}
reason = 'unreferenced untagged manifest (orphaned child)';
} else if (
ageMs > staleTaggedRetentionMs &&
tags.every((tag) => !keepTags.has(tag)) &&
tags.every((tag) => managedTag.test(tag) || cacheTag.test(tag))
) {
reason = `stale managed tags older than ${process.env.STALE_TAGGED_RETENTION_DAYS} days`;
}
if (!reason) {
core.info(`keep ${version.id}: ${tagList} (${dates})`);
continue;
}
core.info(
`${dryRun ? 'would delete' : 'delete'} ${version.id}: ${tagList} ${version.name} (${reason}; ${dates})`
);
if (!dryRun) {
await deleteVersion({
...ownerArgs,
package_type: 'container',
package_name: packageName,
package_version_id: version.id,
});
}
deleted += 1;
}
core.notice(`${dryRun ? 'Would delete' : 'Deleted'} ${deleted} package version(s).`);