36 lines
2.1 KiB
Bash
36 lines
2.1 KiB
Bash
#!/usr/bin/env bash
|
||
# Caller holds its store lock. Keep recent image layers and the host NuGet cache.
|
||
set -euo pipefail
|
||
: "${CONTAINERS_STORAGE_CONF:?an explicit, locked CI Buildah store is required}"
|
||
# 以 root 运行(CI 主机)时存储是 root 的,直接用;只有无特权用户才需要 buildah unshare 进用户命名空间。
|
||
# 这台主机上 buildah unshare 会报 memfd_create: Invalid argument,root 下也用不着它。
|
||
in_userns() {
|
||
if [[ "$(id -u)" == 0 ]]; then "$@"; else buildah unshare "$@"; fi
|
||
}
|
||
# No build is active while the caller holds the exclusive store lock. Remove
|
||
# working containers left by canceled builds before considering old image layers.
|
||
in_userns buildah rm --all >/dev/null 2>&1 || true
|
||
buildah rmi localhost/moshiro-agent-binaries:linux-musl-x64 >/dev/null 2>&1 || true
|
||
# Remove only expired intermediate layers and versioned application images.
|
||
mapfile -t expired < <(buildah images --all --no-trunc --format '{{.ID}} {{.Created}} {{.Name}}:{{.Tag}}' | python3 -c '
|
||
import re,sys,time
|
||
cutoff=time.time()-7*86400
|
||
for line in sys.stdin:
|
||
fields=line.split()
|
||
if len(fields)!=3 or float(fields[1]) >= cutoff:
|
||
continue
|
||
name=fields[2]
|
||
if name in ("<none>:<none>", ":") or re.fullmatch(r"localhost/moshiro-(agent|backend):[0-9][A-Za-z0-9._-]*",name) or re.fullmatch(r"localhost/moshiro-agent-restore:[0-9a-f]{40}-linux-(x64|arm64|musl-arm64)",name):
|
||
print(fields[0])
|
||
')
|
||
for image in "${expired[@]}"; do
|
||
# No force: a layer still referenced by another image/container is retained.
|
||
buildah rmi "$image" >/dev/null 2>&1 || true
|
||
done
|
||
echo "expired build layers considered: ${#expired[@]} (retention: 7 days; NuGet cache retained)"
|
||
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||
# 旧的 Buildah 存储目录的属主可能是映射后的 uid,无特权用户要在用户命名空间里删;清理失败只警告,下次再试,不影响调用方。
|
||
if ! in_userns python3 "$root/ci/cleanup-retired-stores.py" /home/justme/woodpecker/buildah-home; then
|
||
echo 'warning: retired Buildah stores were not cleaned (cleanup failed); the next run retries' >&2
|
||
fi
|