Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ Restoring the cache and filling it are separate problems with separate
lifetimes, so they are separate components:

- **`containerd-image-preload`** (an RPM) answers *restore*. A systemd timer
runs `ctr images import` over every tarball of the cache directory, on boot
and periodically. It is deliberately dumb: a shell script, no daemon, no
Kubernetes client, no registry access. It works on a node whose cluster is
down, and it is idempotent: re-importing what containerd already has
replaces nothing and breaks nothing.
runs `ctr images import` over every tarball of the cache directory whose
images containerd is missing, on boot and periodically. It is deliberately
dumb: a shell script, no daemon, no Kubernetes client, no registry access.
It works on a node whose cluster is down. Archives whose images all show as
complete and unpacked in `ctr images check` are skipped, since re-importing
them costs about twice their size in I/O. See
[rpm/README.md](rpm/README.md#what-it-imports) for how images are matched.

- **`image-cache-agent`** (a Kubernetes DaemonSet) answers *fill*. It watches
`ImageCache` custom resources, pulls the images they point at, extracts the
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ The project is three pieces that meet on a directory:

| Component | What it does |
| --- | --- |
| [`containerd-image-preload`](rpm/) (RPM) | A systemd service and timer that import every tarball of the cache directory into containerd. Runs on boot and every 10 minutes. Needs no Kubernetes, no registry, no network. |
| [`containerd-image-preload`](rpm/) (RPM) | A systemd service and timer that import into containerd the tarballs of the cache directory whose images containerd is missing. Runs on boot and every 10 minutes. Needs no Kubernetes, no registry, no network. |
| [`image-cache-agent`](agent/) (DaemonSet) | A Kubernetes agent that fills the cache: it pulls the images declared by `ImageCache` custom resources, extracts the tarballs they carry into the cache directory, garbage-collects what is no longer declared, and reports per-node progress as node labels. |
| [`imagecachectl`](agent/cmd/imagecachectl/) (command, RPM) | The same fill, once, for a node that has no Kubernetes yet. Reads a registry or a docker archive and writes the tarballs where the agent would have. |

Expand All @@ -45,7 +45,7 @@ cache up to date on a cluster that imports it some other way.
│ reads *.tar
▼
┌──────────────────────────────────────┐
│ containerd-image-preload (systemd) │ ctr images import, every 10 min
│ containerd-image-preload (systemd) │ ctr images import of what is missing, every 10 min
└──────────────────┬───────────────────┘
▼
containerd
Expand Down
40 changes: 34 additions & 6 deletions rpm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,37 @@ below it:

Nothing deeper, and nothing under a hidden directory. Each file goes in with
`ctr -n k8s.io images import --platform "$IMAGE_PLATFORM"`, into the `k8s.io`
namespace, which is where the kubelet looks. Re-importing an image containerd
already has replaces nothing and breaks nothing, which is what makes running
the timer on a short period harmless.
namespace, which is where the kubelet looks.

An archive is skipped when containerd already holds every image in it,
complete and unpacked as `ctr -n k8s.io images check` reports, which saves
re-reading and re-writing it every run. How an image is matched depends on
the archive's format, read the way containerd reads it:

- **OCI archive** (an `index.json`, as `docker save` writes from Docker 25 on,
even next to a `manifest.json`): its `io.containerd.image.name` and
manifest digest, which containerd keeps as is.
- **docker-archive** (a `manifest.json` and no `index.json`, as `skopeo copy
… docker-archive:` and older `docker save` write): each of its `RepoTags`,
named the way containerd names it on import (`pause:3.10` becomes
`docker.io/library/pause:3.10`), and the digest of its image configuration.
containerd writes a manifest of its own for such an image, so the
configuration, copied byte for byte, is what both have in common. The
script hashes it from the archive, and reads the one containerd holds from
the manifest with `ctr content get`, once per image per run.

Otherwise the archive is imported: when it has neither file, an unnamed or
untagged image, an `index.json`, `manifest.json` or configuration over 1 MiB,
when the name points at something other than a single manifest, and when
`ctr` cannot answer. This needs `jq` and GNU `tar`, which the package
requires.

When two archives hold the same image name with different images, the last
one imported wins, as when nothing is skipped. Once the run imports an
archive, it no longer takes the names it could read from that archive as
present, even from one it could not have skipped, so a later archive
holding one of them is imported too. Both are then imported at every
run: give each name to one archive only to have them skipped.

A tarball that fails to import does not stop the ones after it. The run tries
every archive, names each one it could not import, and then exits non-zero, so
Expand All @@ -92,9 +120,9 @@ exits zero: deciding that an empty cache is wrong is the caller's call, not
this script's. A pipeline that reads "wrote to stderr" as "failed" will see
that line, so read the exit status.

Every run ends with one line that says what it did. Under systemd, each line
carries its syslog priority: failures are `err`, a cache with nothing left is
`warning`, the rest is `info`. So `journalctl -u containerd-image-preload -p err`
Every run ends with one line that says what it did. Under systemd, each line carries its syslog priority: failures are
`err`, a cache with nothing left and a containerd that could not list its
images are `warning`, the rest is `info`. So `journalctl -u containerd-image-preload -p err`
shows only the failed imports. The journal adds the timestamps. Run by hand,
the script prints plain lines with no priority prefix. Lines that `ctr` writes
itself stay at `info`.
Expand Down
5 changes: 3 additions & 2 deletions rpm/build.Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Build image for the containerd-image-preload RPM.
# Provides the RHEL-family RPM build toolchain (rpm-build + rpmlint) plus
# shellcheck and systemd to validate the shipped script and unit files.
# shellcheck and systemd to validate the shipped script and unit files, and
# jq and tar for the script's tests.
# The base image (Rocky Linux 8 or 9) is provided by the caller; see the Makefile.
ARG BUILD_IMAGE
FROM ${BUILD_IMAGE}

RUN dnf install -y --setopt=skip_missing_names_on_install=False \
rpm-build rpmlint rpmdevtools systemd && \
rpm-build rpmlint rpmdevtools systemd jq tar && \
dnf install -y epel-release && \
dnf install -y ShellCheck bats && \
dnf clean all
Expand Down
2 changes: 2 additions & 0 deletions rpm/containerd-image-preload.spec
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Source3: containerd-image-preload.sysconfig

BuildArch: noarch
Requires: containerd
Requires: jq
Requires: tar

%description
A systemd service and timer that periodically import container image tarballs
Expand Down
201 changes: 193 additions & 8 deletions rpm/sources/containerd-image-preload.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,193 @@ info() { log 6 1 "$@"; }
warn() { log 4 2 "$@"; }
error() { log 3 2 "$@"; }

scanned=0
# Archive metadata larger than this is not trusted: the archive is imported.
MEMBER_MAX_BYTES=1048576

# "name digest" of each image containerd holds complete and unpacked.
# ctr exits non-zero when any image fails its check but still prints every
# row, so only a missing header means containerd did not answer. With no
# image at all, it prints nothing, not even the header, and succeeds.
ready_images() {
local table status=0
table="$(ctr -n k8s.io images check 2> /dev/null)" || status=$?
if [ -z "${table}" ] && [ "${status}" -eq 0 ]; then
return 0
fi
[[ "${table}" == REF* ]] || return 1
awk 'NR > 1 && $4 == "complete" && $NF == "true" { print $1, $3 }' <<< "${table}"
}

Comment thread
riadelhajjaji-scality marked this conversation as resolved.
Resolved
# One file of an archive, cut at MEMBER_MAX_BYTES (a cut file fails to parse
# or to hash). The name can come from the archive: `--` stops GNU tar from
# reading it as an option, --no-wildcards from matching `*` or `[` as a glob.
archive_member() {
tar --seek --occurrence=1 --no-wildcards -xOf "$1" -- "$2" 2> /dev/null |
head -c "${MEMBER_MAX_BYTES}"
}

# "name manifest-digest" of each image in an OCI archive. Fails when an image
# is unnamed.
oci_archive_images() {
archive_member "$1" index.json |
jq -r '
.manifests
| if length > 0
and all(.[]; (.annotations["io.containerd.image.name"] // "") != "")
then .[] | "\(.annotations["io.containerd.image.name"]) \(.digest)"
else error("not every image is named") end
' 2> /dev/null
}

# The name containerd gives a docker-archive tag on import, as Docker does.
normalize_name() {
local name="$1" domain path
domain="${name%%/*}"
path="${name#*/}"
# The first component is a registry only if it looks like a host.
if [[ "${name}" != */* ]] ||
[[ "${domain}" != *[.:[:upper:]]* && "${domain}" != localhost ]]; then
domain=docker.io
path="${name}"
fi
if [ "${domain}" = index.docker.io ]; then
domain=docker.io
fi
if [ "${domain}" = docker.io ] && [[ "${path}" != */* ]]; then
path="library/${path}"
fi
if [[ "${path##*/}" != *:* ]]; then
path="${path}:latest"
fi
printf '%s/%s\n' "${domain}" "${path}"
}

# "name config-digest" of each tag in a docker-archive. containerd writes its
# own manifest on import, so the configuration is what both share; its digest
# is the hash of the file. Fails on an untagged image, or on a tag or path
# that is empty, holds white space, or (for a path) starts with a dash.
docker_archive_images() {
local entries name config sum
local -A config_digests=()
entries="$(archive_member "$1" manifest.json |
jq -r '
if type == "array" and length > 0
and all(.[]; (.Config | type) == "string"
Comment thread
riadelhajjaji-scality marked this conversation as resolved.
Resolved
and (.Config | test("^[^-\\s][^\\s]*$"))
and ((.RepoTags // []) | type) == "array"
and ((.RepoTags // []) | length) > 0
and all(.RepoTags[]; type == "string" and test("^[^\\s]+$")))
then .[] | .Config as $config | .RepoTags[] | "\(.) \($config)"
else error("not every image is tagged") end
' 2> /dev/null)" || return 1
while read -r name config; do
if [ -z "${config_digests[${config}]+set}" ]; then
sum="$(archive_member "$1" "${config}" | sha256sum)" || return 1
config_digests[${config}]="sha256:${sum%% *}"
fi
printf '%s %s\n' "$(normalize_name "${name}")" "${config_digests[${config}]}"
done <<< "${entries}"
}

# Every name an import of the archive can set, read leniently: an archive
# rejected for a skip still moves the names it does have.
oci_archive_names() {
archive_member "$1" index.json |
jq -r '
.manifests | arrays | .[] | objects
| .annotations | objects | .["io.containerd.image.name"]
| strings | select(test("^[^\\s]+$"))
' 2> /dev/null
}

docker_archive_names() {
local tag
archive_member "$1" manifest.json |
jq -r '
arrays | .[] | objects | .RepoTags | arrays | .[]
| strings | select(test("^[^\\s]+$"))
' 2> /dev/null |
while IFS= read -r tag; do
normalize_name "${tag}"
done
}

# Configuration digest per manifest, cached for the run (empty if unreadable).
declare -A ready_configs=()

# Sets config to the configuration digest of the ready image named $1. Fails
# when there is none, or when the name points at an index.
ready_config() {
local manifest
manifest="$(name="$1" awk '$1 == ENVIRON["name"] { print $2; exit }' <<< "${ready}")"
[ -n "${manifest}" ] || return 1
if [ -z "${ready_configs[${manifest}]+set}" ]; then
ready_configs[${manifest}]="$(ctr -n k8s.io content get "${manifest}" 2> /dev/null |
head -c "${MEMBER_MAX_BYTES}" |
jq -er '.config.digest | strings' 2> /dev/null)" ||
ready_configs[${manifest}]=""
fi
config="${ready_configs[${manifest}]}"
[ -n "${config}" ]
}

# Names of the archive last given to already_imported.
archive_names=""

# True when containerd already holds every image of the archive. Like
# containerd, it prefers index.json when manifest.json is there too.
already_imported() {
local members images line name digest config
archive_names=""
[ -n "${ready}" ] || return 1
members="$(tar --seek -tf "$1" 2> /dev/null)" || return 1
if grep -qxF index.json <<< "${members}"; then
archive_names="$(oci_archive_names "$1")" || true
images="$(oci_archive_images "$1")" || return 1
[ -n "${images}" ] || return 1
Comment thread
riadelhajjaji-scality marked this conversation as resolved.
Resolved
while IFS= read -r line; do
grep -qxF -- "${line}" <<< "${ready}" || return 1
done <<< "${images}"
elif grep -qxF manifest.json <<< "${members}"; then
archive_names="$(docker_archive_names "$1")" || true
images="$(docker_archive_images "$1")" || return 1
[ -n "${images}" ] || return 1
while read -r name digest; do
ready_config "${name}" || return 1
[ "${config}" = "${digest}" ] || return 1
done <<< "${images}"
else
return 1
fi
}

# Drops the names of the archive just imported (or failed: it may have moved
# some) from ready, so a later archive holding the same name with another
# image is imported too and the last one wins, instead of the name switching
# at every run.
forget_archive_names() {
[ -n "${archive_names}" ] || return 0
ready="$(awk 'NR == FNR { names[$1]; next } !($1 in names)' \
<(printf '%s\n' "${archive_names}") <(printf '%s\n' "${ready}"))"
}

archives=("${IMAGE_CACHE_DIR}"/*.tar "${IMAGE_CACHE_DIR}"/*/*.tar)
scanned=${#archives[@]}
skipped=0
current=0
failures=0

# If containerd does not answer at all, every archive is imported.
ready=""
if [ "${scanned}" -ne 0 ] && ! ready="$(ready_images)"; then
warn "Could not list the images containerd has, importing every archive"
ready=""
fi

# Tars live flat (provisioning) or in per-resource subdirectories (agent).
# An archive containerd cannot read must not keep the others out, so every
# archive is tried and each failure is named as it happens.
for tar in "${IMAGE_CACHE_DIR}"/*.tar "${IMAGE_CACHE_DIR}"/*/*.tar; do
scanned=$((scanned + 1))
for tar in "${archives[@]}"; do
# The glob expanded before the first import, and the agent takes a
# resource's directory away to collect it and again to swap a fresh
# extraction in. An archive that is already gone when its turn comes is
Expand All @@ -49,32 +227,39 @@ for tar in "${IMAGE_CACHE_DIR}"/*.tar "${IMAGE_CACHE_DIR}"/*/*.tar; do
skipped=$((skipped + 1))
continue
fi
if already_imported "${tar}"; then
info "Skipping ${tar}, already in containerd"
current=$((current + 1))
continue
fi
info "Importing ${tar}"
if ! ctr -n k8s.io images import --platform "${IMAGE_PLATFORM}" "${tar}"; then
error "Failed to import ${tar}"
failures=$((failures + 1))
fi
Comment thread
riadelhajjaji-scality marked this conversation as resolved.
Resolved
forget_archive_names
done

imported=$((scanned - skipped - failures))
imported=$((scanned - skipped - current - failures))

if [ "${failures}" -ne 0 ]; then
# Say what became of all of them: one torn archive out of forty reads
# nothing like a containerd that is down, and neither reads like a cache
# the agent emptied while the run was walking it.
error "Failed to import ${failures} of the ${scanned} cached archives" \
"(${imported} imported, ${skipped} no longer there)"
"(${imported} imported, ${current} already in containerd," \
"${skipped} no longer there)"
exit 1
fi

if [ "${scanned}" -eq 0 ]; then
info "No cached archives to import in ${IMAGE_CACHE_DIR}"
elif [ "${imported}" -eq 0 ]; then
# Nothing failed, yet nothing made it in either. A whole cache going away
elif [ "${skipped}" -eq "${scanned}" ]; then
# Nothing failed, yet nothing was there either. A whole cache going away
# under the run is legitimate (every resource collected at once) and is not
# this script's call to make, but it must not pass for a quiet success.
warn "None of the ${scanned} cached archives were still there to import"
else
info "Imported ${imported} of the ${scanned} cached archives" \
"(${skipped} no longer there)"
"(${current} already in containerd, ${skipped} no longer there)"
fi
5 changes: 5 additions & 0 deletions rpm/test/package.bats
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ assert_linter_clean() {
rpm -qpR "$RPM" | grep -qx "containerd"
}

@test "package requires jq and tar, which the script reads archive indexes with" {
rpm -qpR "$RPM" | grep -qx "jq"
rpm -qpR "$RPM" | grep -qx "tar"
}

@test "package ships the expected files" {
run rpm -qlp "$RPM"
[ "$status" -eq 0 ]
Expand Down
Loading
Loading