Compare commits

..
Author SHA1 Message Date
reyesj2 1a717897f9 collect image pool results in one helper
Verify, copy and pull each repeated the same log, sort and summary loop;
one pool_collect helper now does it for all three, byte-identically.
2026-12-02 13:06:19 -06:00
reyesj2 316bfbeadc retry like docker pull and fail image setup clearly
Verify and copy now retry 5 times 30 s apart, matching the old pull budget. The preflight stays quick: it stops at once on not found or
access denied, retries other errors once, and takes Ctrl-C. A job that leaves no result counts as failed, .rc files are written atomically, and each failed phase ends with one line naming the failed and skipped images. Job count and timeouts are internal constants instead of env overrides.
2026-11-30 17:39:03 -06:00
reyesj2 5cb6fd7057 fail fast when the registry or an image fails
One inspect preflight turns an unreachable registry into about a
minute of retries instead of one round per image. The pool stops
launching after a finished job fails and logs every skipped image;
the caller's rc loop still reports the failures.
2026-11-29 17:51:04 -06:00
reyesj2 ddbf3e971a verify images with buildx instead of a registry client
Read the manifest with imagetools inspect --raw and the config by
manifest digest, each under timeout and retry_cmd. Every failure in
this path gets its own message, and the .sig download is bounded by
timeouts and --fail.
2026-11-29 17:51:03 -06:00
reyesj2 dd4165fa56 kill the whole image job pool on INT and TERM
Track the pool PIDs and their descendants, TERM then KILL them, and
exit 130/143. Restore the caller's traps afterwards, since soup
installs its own EXIT and ERR handlers.
2026-11-29 17:51:03 -06:00
reyesj2 eb3ff80154 copy and pull images through argv helpers
Add retry_cmd, which runs an argv array instead of an eval'd command
string, and use it for the buildx copy and the local pull. Pull the
digest gpg verified and tag it, so a re-pushed tag cannot be installed.
2026-11-29 17:51:03 -06:00
reyesj2 f78382fee2 revert so-image-pull and so-tcpreplay to 3/dev
Drop the embedded-registry shortcut from both scripts so they match
3/dev byte for byte, and delete the three so-image-common helpers
that only those shortcuts used.
2026-11-29 17:51:03 -06:00
reyesj2 274803b930 verify, copy and pull images in parallel
Run each step with up to SO_IMAGE_PARALLEL images at a time (default 4).
Copies run in waves whose images share no layer that is not stored yet,
so each layer is still downloaded once. Nothing is copied or pulled unless
every image verified. Only the pool's own PIDs are waited on, because soup
can have its own background jobs in the same shell.
2026-11-29 17:42:04 -06:00
reyesj2 e321b92248 mount shared layers across embedded registry repositories
The registry links blobs per repository and buildx cannot mount across
registries, so a layer shared by several images was still downloaded once
per image. Before each copy, link layers an earlier image already stored
into the target repository.
2026-11-29 17:42:04 -06:00
reyesj2 b6a597bb05 verify images from registry metadata and download each image once
update_docker_containers ran docker pull on every image for the gpg check,
then the buildx copy fetched the same layers from ghcr.io again, so each
image was downloaded about twice. Build the signed .txt from the manifest
and config blob instead, byte-identical to the old docker inspect layout,
copy the verified digest once, and fill the local image store from the
embedded registry. so-image-pull and so-tcpreplay load from the embedded
registry when it already has the image.
2026-11-29 17:42:04 -06:00
reyesj2 2f97a2c283 keep GODEBUG local to the buildx copy and retry instead of docker push
Exporting GODEBUG leaked http2client=0 into every later Go program the
script runs, and prepending it let an existing http2client setting win. Set
it as a prefix assignment on the copy only, and append it so it takes
effect. The docker push fallback cannot work on Docker 29 with the
containerd image store, which is why the copy uses buildx imagetools
create, so retry the copy instead.
2026-11-29 17:42:04 -06:00
reyesj2 303fefe84d Merge #16343: force HTTP/1.1 for buildx copies to the embedded registry
Community fix for https://github.com/Security-Onion-Solutions/securityonion/issues/16342 by @Morochief.
2026-11-20 16:47:03 -06:00
Jorge Reyes 399219b735 Merge pull request #16406 from Security-Onion-Solutions/reyesj2/589
Fix global_overrides dropped by in-place pillar pop
2026-11-19 08:49:50 -06:00
reyesj2 180a4814f9 Fix global_overrides dropped by in-place pillar pop in template.map.jinja 2026-11-18 10:47:54 -06:00
Morochief 8a1179d403 FIX: Resolve HTTP/2 PROTOCOL_ERROR during soup image pull (fixes #16342) 2026-10-24 12:48:00 -03:00
5 changed files with 541 additions and 137 deletions

No files matched your search

+533 -82
View File
@@ -10,6 +10,17 @@
# NOTE: This script depends on so-common
IMAGEREPO=security-onion-solutions
STATUS_CONF='/opt/so/conf/so-status/so-status.conf'
# PIDs of the current launch_pool children, so the INT/TERM trap can kill them.
POOL_PIDS=()
_pool_tree=()
IMAGE_PARALLEL_JOBS=4
IMAGE_INSPECT_TIMEOUT=120
IMAGE_RETRIES=5
IMAGE_RETRY_DELAY=30
# The preflight is a quick check, not a retry budget: one retry at most, and a
# definite answer from the registry ends it right away.
PREFLIGHT_ATTEMPTS=2
PREFLIGHT_RETRY_DELAY=10
# shellcheck disable=SC2120
container_list() {
@@ -79,6 +90,420 @@ container_list() {
fi
}
registry_host() {
if [ -z "$HOSTNAME" ]; then
HOSTNAME=$(hostname)
fi
printf '%s' "$HOSTNAME"
}
manifest_blob_digests() {
jq -r '(.config.digest // empty), (.layers[]? | .digest)' "$1"
}
# Registries link blobs per repo and buildx cannot mount across registries, so
# pre-link shared layers or every image re-downloads them from ghcr.io.
mount_shared_blobs() {
local host=$1
local target_repo=$2
local manifest_file=$3
local log_file=$4
local -n blob_repo=$5
local digest source_repo code
while IFS= read -r digest; do
if [ -z "$digest" ]; then
continue
fi
source_repo="${blob_repo[$digest]:-}"
if [ -z "$source_repo" ] || [ "$source_repo" == "$target_repo" ]; then
continue
fi
code=$(curl -sk --connect-timeout 5 --max-time 30 -o /dev/null -w '%{http_code}' -X POST \
"https://${host}:5000/v2/${IMAGEREPO}/${target_repo}/blobs/uploads/?mount=${digest}&from=${IMAGEREPO}/${source_repo}" \
2>> "$log_file")
if [ "$code" != "201" ]; then
echo "Could not pre-link $digest from $source_repo into $target_repo (HTTP ${code:-error}), buildx will download it" >> "$log_file"
fi
done < <(manifest_blob_digests "$manifest_file")
}
record_shared_blobs() {
local target_repo=$1
local manifest_file=$2
local -n blob_repo=$3
local digest
while IFS= read -r digest; do
if [ -n "$digest" ] && [ -z "${blob_repo[$digest]:-}" ]; then
blob_repo["$digest"]=$target_repo
fi
done < <(manifest_blob_digests "$manifest_file")
}
image_ref() { # image_ref <image:tag> => the full registry reference
printf '%s/%s/%s' "$CONTAINER_REGISTRY" "$IMAGEREPO" "$1"
}
# One small function per inspect: retry_cmd logs its attempts on stdout, so the
# command's own output is redirected to its file here.
fetch_manifest() { # fetch_manifest <ref> <out file>
timeout "$IMAGE_INSPECT_TIMEOUT" docker buildx imagetools inspect --raw "$1" >"$2"
}
# buildx's --format output is the contract with the signed .txt, so it stays in
# one place that is easy to adjust.
fetch_config() { # fetch_config <ref> <out file>
timeout "$IMAGE_INSPECT_TIMEOUT" docker buildx imagetools inspect \
--format '{{json .Image}}' "$1" >"$2"
}
# The ES image follows the elasticsearch version, everything else the SO
# version. Prints "<image>:<tag> <signature url>".
resolve_image() { # resolve_image <image>
local i=$1
local image_version
if [[ " ${IMAGES_USING_ES_VERSION[*]} " =~ [[:space:]]${i}[[:space:]] ]]; then
# this is an es container so use version defined in elasticsearch defaults.yaml
local UPDATE_DIR='/tmp/sogh/securityonion'
if [ ! -d "$UPDATE_DIR" ]; then
UPDATE_DIR=/securityonion
fi
local v1=0
local v2=0
if [[ -f "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" ]]; then
v1=$(grep -E " +version: " "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
fi
if [[ -f "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" ]]; then
v2=$(grep -E " +version: " "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
fi
image_version=$(compare_es_versions "$v1" "$v2")
printf '%s:%s%s https://sigs.securityonion.net/es-%s/%s:%s%s.sig\n' \
"$i" "$image_version" "$IMAGE_TAG_SUFFIX" "$image_version" "$i" "$image_version" "$IMAGE_TAG_SUFFIX"
else
# this is not an es container so use the so version for the version
image_version=$VERSION
printf '%s:%s%s https://sigs.securityonion.net/%s/%s:%s%s.sig\n' \
"$i" "$image_version" "$IMAGE_TAG_SUFFIX" "$image_version" "$i" "$image_version" "$IMAGE_TAG_SUFFIX"
fi
}
verify_trusted_image() {
local i=$1
local IMAGE_LOG=$SIGNPATH/$i.verify.log
local image sig_url
read -r image sig_url < <(resolve_image "$i")
local image_name=$i
local manifest_file=$SIGNPATH/$image.manifest
local config_file=$SIGNPATH/$image.config
local REF
REF=$(image_ref "$image")
local VERIFIED_REF
local rc=0
local digest_re='^sha256:[a-f0-9]{64}$'
retry_cmd "$IMAGE_RETRIES" "$IMAGE_RETRY_DELAY" fetch_manifest "$REF" "$manifest_file" >>"$IMAGE_LOG" 2>&1 || rc=$?
if [ "$rc" -ne 0 ]; then
echo "Could not fetch manifest for $image, please ensure connectivity to $CONTAINER_REGISTRY" >>"$IMAGE_LOG" 2>&1
echo "Command failed with error $rc" >>"$IMAGE_LOG" 2>&1
return 1
fi
if [ ! -s "$manifest_file" ] || ! jq -e . "$manifest_file" >/dev/null 2>&1; then
echo "Unable to read the manifest for $image: empty or not JSON" >>"$IMAGE_LOG" 2>&1
return 1
fi
# The sig covers these exact bytes, so an index would sign the wrong document.
if jq -e '.manifests | type == "array"' "$manifest_file" >/dev/null 2>&1; then
echo "$image manifest is a multi-platform index, expected a single manifest" >>"$IMAGE_LOG" 2>&1
return 1
fi
local manifest_digest
manifest_digest=$(sha256sum "$manifest_file" | awk '{print $1}')
local config_digest
config_digest=$(jq -r '.config.digest // empty' "$manifest_file")
if [ -z "$manifest_digest" ] || [ -z "$config_digest" ] || [ "$config_digest" = "null" ]; then
echo "Unable to read the manifest for $image: no config digest" >>"$IMAGE_LOG" 2>&1
return 1
fi
# Every digest ends up in a URL (blob fetches, blob mounts, the wave
# planner), so one malformed digest rejects the whole manifest.
if [[ ! $config_digest =~ $digest_re ]]; then
echo "Unable to inspect $image: invalid config digest '$config_digest'" >>"$IMAGE_LOG" 2>&1
return 1
fi
local layer_digest
while IFS= read -r layer_digest; do
if [ -z "$layer_digest" ]; then
continue
fi
if [[ ! $layer_digest =~ $digest_re ]]; then
echo "Unable to inspect $image: invalid layer digest '$layer_digest'" >>"$IMAGE_LOG" 2>&1
return 1
fi
done < <(jq -r '.layers[]? | .digest' "$manifest_file")
rc=0
# By digest, not by tag: a tag can be re-pushed between the two calls, and the
# .txt must describe the manifest bytes that sha256sum and the sig cover.
VERIFIED_REF="${CONTAINER_REGISTRY}/${IMAGEREPO}/${image_name}@sha256:${manifest_digest}"
retry_cmd "$IMAGE_RETRIES" "$IMAGE_RETRY_DELAY" fetch_config "$VERIFIED_REF" "$config_file" >>"$IMAGE_LOG" 2>&1 || rc=$?
if [ "$rc" -ne 0 ]; then
echo "Could not fetch image config for $image, please ensure connectivity to $CONTAINER_REGISTRY" >>"$IMAGE_LOG" 2>&1
echo "Command failed with error $rc" >>"$IMAGE_LOG" 2>&1
return 1
fi
if [ ! -s "$config_file" ]; then
echo "Unable to read the config for $image" >>"$IMAGE_LOG" 2>&1
return 1
fi
# Get signature
rc=0
curl --fail --connect-timeout 10 --max-time 120 --retry 5 --retry-delay 60 -sSL \
-A "$CURLTYPE/$CURRENTVERSION/$OS/$(uname -r)" \
--output "$SIGNPATH/$image.sig" "$sig_url" >>"$IMAGE_LOG" 2>&1 || rc=$?
if [ "$rc" -ne 0 ]; then
echo "Could not pull signature file for $image, please ensure connectivity to https://sigs.securityonion.net " >>"$IMAGE_LOG" 2>&1
echo "Command failed with error $rc" >>"$IMAGE_LOG" 2>&1
return 1
fi
# .txt layout must stay byte-identical to the old `docker inspect | jq` output
# because the gpg signature is verified against it.
if ! printf '%s\n' "\"${VERIFIED_REF}\"" >"$SIGNPATH/$image.txt"; then
echo "Unable to write the signed ref line for $image" >>"$IMAGE_LOG" 2>&1
return 1
fi
if ! jq ".created, .rootfs.diff_ids" "$config_file" >>"$SIGNPATH/$image.txt"; then
echo "Unable to extract created and diff_ids for $image" >>"$IMAGE_LOG" 2>&1
return 1
fi
local GPGTEST
if ! GPGTEST=$(gpg --verify "$SIGNPATH/$image.sig" "$SIGNPATH/$image.txt" 2>&1); then
echo "Signature verification failed for $image. Details:" >>"$IMAGE_LOG" 2>&1
echo "$GPGTEST" >>"$IMAGE_LOG" 2>&1
return 1
fi
printf '%s\n%s\n%s\n' "$image" "$VERIFIED_REF" "$manifest_file" >"$SIGNPATH/$i.ref"
return 0
}
# retry()/run_check_net_err() eval their command string, so the argv helper is
# used for anything that must not be re-parsed by the shell.
retry_cmd() {
local max_attempts=$1
local delay=$2
shift 2
local attempt=1 rc=0
while :; do
if "$@"; then
return 0
else
rc=$?
fi
echo "Command failed with error $rc (attempt $attempt of $max_attempts): $*"
if [ "$attempt" -ge "$max_attempts" ]; then
return $rc
fi
attempt=$((attempt + 1))
sleep "$delay"
done
}
copy_verified_image() {
local i=$1
local IMAGE_LOG=$SIGNPATH/$i.copy.log
local image VERIFIED_REF manifest_file
{
read -r image
read -r VERIFIED_REF
read -r manifest_file
} <"$SIGNPATH/$i.ref"
local host
host=$(registry_host)
mount_shared_blobs "$host" "$i" "$manifest_file" "$IMAGE_LOG" pushed_blob_repo
# imagetools create, not docker push: Docker 29's containerd store cannot push a
# freshly pulled image. GODEBUG prefix keeps http2client=0 local (#16342).
# It reads from ghcr.io, so it gets the same budget as the verify fetches.
retry_cmd "$IMAGE_RETRIES" "$IMAGE_RETRY_DELAY" env GODEBUG="${GODEBUG:+${GODEBUG},}http2client=0" \
docker buildx imagetools create --tag "${host}:5000/${IMAGEREPO}/${image}" "$VERIFIED_REF" \
>>"$IMAGE_LOG" 2>&1 || {
echo "Unable to copy $image to embedded registry" >>"$IMAGE_LOG" 2>&1
return 1
}
return 0
}
pull_verified_image() {
local i=$1
local IMAGE_LOG=$SIGNPATH/$i.pull.log
local image VERIFIED_REF
{
read -r image
read -r VERIFIED_REF
} <"$SIGNPATH/$i.ref"
local host
host=$(registry_host)
# Pull by the digest that gpg verified, not by the mutable tag a compromised
# grid node could have re-pushed. Keep the tag name visible to `docker images`
# and to the salt checks that look for it.
local digest=${VERIFIED_REF#*@}
local digest_ref="${host}:5000/${IMAGEREPO}/${image%:*}@${digest}"
local tag_ref="${host}:5000/${IMAGEREPO}/${image}"
retry_cmd 3 10 docker pull "$digest_ref" >>"$IMAGE_LOG" 2>&1 || {
echo "Unable to pull $image from embedded registry" >>"$IMAGE_LOG" 2>&1
return 1
}
if ! docker tag "$digest_ref" "$tag_ref" >>"$IMAGE_LOG" 2>&1; then
echo "Unable to tag $image" >>"$IMAGE_LOG" 2>&1
return 1
fi
return 0
}
log_downloading() {
echo "Downloading $1" >> "$LOG_FILE" 2>&1
}
# Kill a pool job and everything it spawned: in a non-interactive shell the
# background docker/curl children ignore SIGINT, so killing only the subshell
# would leave them writing to $SIGNPATH. Only PIDs the pool started are walked.
pool_collect_tree() { # pool_collect_tree <pid>; appends to _pool_tree
local pid=$1
local child
_pool_tree+=("$pid")
while IFS= read -r child; do
if [ -n "$child" ]; then
pool_collect_tree "$child"
fi
done < <(pgrep -P "$pid" 2>/dev/null)
}
_pool_abort() { # _pool_abort <exit code>
local code=$1
local pid
trap '' INT TERM
_pool_tree=()
# Skipping reaped PIDs matters: their numbers may already belong to an
# unrelated process, whose tree would then be killed as root.
for pid in "${POOL_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
pool_collect_tree "$pid"
fi
done
for pid in "${_pool_tree[@]}"; do
kill -TERM "$pid" 2>/dev/null || true
done
sleep 2
for pid in "${_pool_tree[@]}"; do
kill -KILL "$pid" 2>/dev/null || true
done
exit "$code"
}
# Fail fast: once a finished job of this pool failed, no new job is launched, so
# an unreachable registry costs one round of retries instead of one per image.
pool_failed() { # pool_failed <phase> <image>...
local phase=$1
shift
local img rc
for img in "$@"; do
# No .rc yet means the job is still running, so it is not a failure.
if rc=$(cat "$SIGNPATH/$img.$phase.rc" 2>/dev/null) && [ "$rc" != "0" ]; then
return 0
fi
done
return 1
}
# Append one phase's per-image logs, then name what failed or was skipped.
pool_collect() { # pool_collect <phase> <image>...; non-zero if any did not pass
local phase=$1
shift
local img failed=0
local -a bad=() skipped=()
for img in "$@"; do
cat "$SIGNPATH/$img.$phase.log" >> "$LOG_FILE" 2>/dev/null
if [ ! -f "$SIGNPATH/$img.$phase.rc" ]; then
skipped+=("$img")
failed=1
elif [ "$(cat "$SIGNPATH/$img.$phase.rc" 2>/dev/null)" != "0" ]; then
bad+=("$img")
failed=1
fi
done
if [ "$failed" -ne 0 ]; then
echo "$phase failed: ${bad[*]:-none}; skipped: ${skipped[*]:-none}" >> "$LOG_FILE" 2>&1
return 1
fi
return 0
}
launch_pool() {
local func=$1
local phase=$2
local jobs=$3
local hook=$4
shift 4
local -a active=() still=() launched=()
local img pid rc
local stop=0
POOL_PIDS=()
local saved_int saved_term
saved_int=$(trap -p INT)
saved_term=$(trap -p TERM)
trap '_pool_abort 130' INT
trap '_pool_abort 143' TERM
for img in "$@"; do
if [ "$stop" -ne 0 ]; then
# No .rc is written, so the caller counts this image as failed too.
echo "Skipped $img: an earlier image failed" >>"$SIGNPATH/$img.$phase.log" 2>&1
continue
fi
if [ -n "$hook" ]; then
"$hook" "$img"
fi
(
("$func" "$img") >>"$SIGNPATH/$img.$phase.log" 2>&1
rc=$?
# Write then rename: a truncated .rc reads as a failure to pool_failed.
echo "$rc" >"$SIGNPATH/$img.$phase.rc.tmp"
mv "$SIGNPATH/$img.$phase.rc.tmp" "$SIGNPATH/$img.$phase.rc"
) &
pid=$!
POOL_PIDS+=("$pid")
active+=("$pid")
launched+=("$img")
while [ ${#active[@]} -ge "$jobs" ]; do
wait -n "${active[@]}" 2>/dev/null || true
still=()
for pid in "${active[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
still+=("$pid")
fi
done
active=("${still[@]}")
if [ "$stop" -eq 0 ] && pool_failed "$phase" "${launched[@]}"; then
stop=1
fi
done
done
# Only wait on PIDs started here: soup may run its own background jobs in this
# shell (e.g. the grid highstate), and a bare `wait` would block on those.
if [ ${#POOL_PIDS[@]} -gt 0 ]; then
wait "${POOL_PIDS[@]}" 2>/dev/null || true
fi
# Restore whatever the caller had; soup installs its own EXIT/ERR handlers.
eval "${saved_int:-trap - INT}"
eval "${saved_term:-trap - TERM}"
}
update_docker_containers() {
local CURLTYPE=$1
local IMAGE_TAG_SUFFIX=$2
@@ -130,91 +555,117 @@ update_docker_containers() {
grep -q "so-logscan" "$STATUS_CONF" && TRUSTED_CONTAINERS+=("so-logscan")
fi
# Download the containers from the interwebs
for i in "${TRUSTED_CONTAINERS[@]}"
do
if [ -z "$PROGRESS_CALLBACK" ]; then
echo "Downloading $i" >> "$LOG_FILE" 2>&1
else
$PROGRESS_CALLBACK $i
fi
local -A pushed_blob_repo=()
if [[ " ${IMAGES_USING_ES_VERSION[*]} " =~ [[:space:]]${i}[[:space:]] ]]; then
# this is an es container so use version defined in elasticsearch defaults.yaml
local UPDATE_DIR='/tmp/sogh/securityonion'
if [ ! -d "$UPDATE_DIR" ]; then
UPDATE_DIR=/securityonion
fi
local v1=0
local v2=0
if [[ -f "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" ]]; then
v1=$(egrep " +version: " "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
fi
if [[ -f "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" ]]; then
v2=$(egrep " +version: " "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
fi
local highest_es_version=$(compare_es_versions "$v1" "$v2")
local image=$i:$highest_es_version$IMAGE_TAG_SUFFIX
local sig_url=https://sigs.securityonion.net/es-$highest_es_version/$image.sig
else
# this is not an es container so use the so version for the version
local image=$i:$VERSION$IMAGE_TAG_SUFFIX
local sig_url=https://sigs.securityonion.net/$VERSION/$image.sig
fi
# Pull down the trusted docker image
run_check_net_err \
"docker pull $CONTAINER_REGISTRY/$IMAGEREPO/$image" \
"Could not pull $image, please ensure connectivity to $CONTAINER_REGISTRY" >> "$LOG_FILE" 2>&1
local jobs=$IMAGE_PARALLEL_JOBS
# Get signature
run_check_net_err \
"curl --retry 5 --retry-delay 60 -A '$CURLTYPE/$CURRENTVERSION/$OS/$(uname -r)' $sig_url --output $SIGNPATH/$image.sig" \
"Could not pull signature file for $image, please ensure connectivity to https://sigs.securityonion.net " \
noretry >> "$LOG_FILE" 2>&1
# Dump our hash values
DOCKERINSPECT=$(docker inspect $CONTAINER_REGISTRY/$IMAGEREPO/$image)
echo "$DOCKERINSPECT" | jq ".[0].RepoDigests[] | select(. | contains(\"$CONTAINER_REGISTRY\"))" > $SIGNPATH/$image.txt
echo "$DOCKERINSPECT" | jq ".[0].Created, .[0].RootFS.Layers" >> $SIGNPATH/$image.txt
if [[ $? -ne 0 ]]; then
echo "Unable to inspect $image" >> "$LOG_FILE" 2>&1
exit 1
fi
GPGTEST=$(gpg --verify $SIGNPATH/$image.sig $SIGNPATH/$image.txt 2>&1)
if [[ $? -eq 0 ]]; then
if [[ -z "$SKIP_TAGPUSH" ]]; then
# Tag it with the new registry destination
if [ -z "$HOSTNAME" ]; then
HOSTNAME=$(hostname)
fi
docker tag $CONTAINER_REGISTRY/$IMAGEREPO/$image $HOSTNAME:5000/$IMAGEREPO/$image >> "$LOG_FILE" 2>&1 || {
echo "Unable to tag $image" >> "$LOG_FILE" 2>&1
exit 1
}
# Push to the embedded registry via a registry-to-registry copy. Avoids
# `docker push`, which on Docker 29.x with the containerd image store
# represents freshly-pulled images as an index whose layer content
# isn't reachable through the push path. The local `docker tag` above
# is preserved so so-image-pull's `:5000` existence check still works.
# Pin to the digest already gpg-verified above so we copy exactly the
# bytes we approved.
local VERIFIED_REF
VERIFIED_REF=$(echo "$DOCKERINSPECT" | jq -r ".[0].RepoDigests[] | select(. | contains(\"$CONTAINER_REGISTRY\"))" | head -n 1)
if [ -z "$VERIFIED_REF" ] || [ "$VERIFIED_REF" = "null" ]; then
echo "Unable to determine verified digest for $image" >> "$LOG_FILE" 2>&1
exit 1
fi
docker buildx imagetools create --tag $HOSTNAME:5000/$IMAGEREPO/$image "$VERIFIED_REF" >> "$LOG_FILE" 2>&1 || {
echo "Unable to copy $image to embedded registry" >> "$LOG_FILE" 2>&1
exit 1
}
fi
else
echo "There is a problem downloading the $image image. Details: " >> "$LOG_FILE" 2>&1
echo "" >> "$LOG_FILE" 2>&1
echo $GPGTEST >> "$LOG_FILE" 2>&1
# Nothing is copied or pulled unless every image verified (a bad signature
# publishes nothing). The hook runs in the parent: it mutates caller globals.
local progress_hook
if [ -z "$PROGRESS_CALLBACK" ]; then
progress_hook=log_downloading
else
progress_hook=$PROGRESS_CALLBACK
fi
# One preflight before the pool, so every verify job does not spend the long
# retry budget in parallel. It is a quick check: a definite answer from the
# registry ends it at once, and only an unclear error gets one more try.
# Upstream registry, not :5000. --foreground keeps it in this shell's process
# group, so Ctrl-C reaches it before launch_pool installs its own trap.
if [ ${#TRUSTED_CONTAINERS[@]} -gt 0 ]; then
local preflight_image preflight_ref preflight_out
local attempt=1 preflight_ok=0 preflight_kind=transient
read -r preflight_image _ < <(resolve_image "${TRUSTED_CONTAINERS[0]}")
preflight_ref=$(image_ref "$preflight_image")
while [ "$attempt" -le "$PREFLIGHT_ATTEMPTS" ]; do
if preflight_out=$(timeout --foreground "$IMAGE_INSPECT_TIMEOUT" \
docker buildx imagetools inspect --raw "$preflight_ref" 2>&1); then
preflight_ok=1
break
fi
# A registry answer never changes on a retry; anything else might.
case "$preflight_out" in
*"not found"*|*"manifest unknown"*) preflight_kind=notfound ;;
*denied*|*unauthorized*) preflight_kind=denied ;;
esac
if [ "$preflight_kind" != transient ]; then
break
fi
attempt=$((attempt + 1))
if [ "$attempt" -le "$PREFLIGHT_ATTEMPTS" ]; then
sleep "$PREFLIGHT_RETRY_DELAY"
fi
done
if [ "$preflight_ok" -ne 1 ]; then
echo "Could not inspect $preflight_ref on $CONTAINER_REGISTRY" >>"$LOG_FILE" 2>&1
case "$preflight_kind" in
notfound) echo "The image or tag for $preflight_image was not found" >>"$LOG_FILE" 2>&1 ;;
denied) echo "Access to $preflight_ref was denied by $CONTAINER_REGISTRY" >>"$LOG_FILE" 2>&1 ;;
*) echo "Check connectivity to $CONTAINER_REGISTRY or the proxy" >>"$LOG_FILE" 2>&1 ;;
esac
echo "$preflight_out" >>"$LOG_FILE" 2>&1
exit 1
fi
fi
launch_pool verify_trusted_image verify "$jobs" "$progress_hook" "${TRUSTED_CONTAINERS[@]}"
pool_collect verify "${TRUSTED_CONTAINERS[@]}" || exit 1
# Verify only from here: no copy and no local pull.
if [[ -n "$SKIP_TAGPUSH" ]]; then
return 0
fi
local -A ref_manifest=()
for i in "${TRUSTED_CONTAINERS[@]}"; do
{ read -r _; read -r _; read -r ref_manifest["$i"]; } < "$SIGNPATH/$i.ref"
done
# Copy in waves: a wave's images share no unstored blob, so each layer is
# downloaded once. The parent must record the blob map (subshells can't).
local -a remaining=("${TRUSTED_CONTAINERS[@]}")
local wave_no=0
while [ ${#remaining[@]} -gt 0 ]; do
wave_no=$((wave_no + 1))
local -a wave=() deferred=()
local -A claimed=()
local img digest conflict
for img in "${remaining[@]}"; do
conflict=0
while IFS= read -r digest; do
[ -z "$digest" ] && continue
[ -n "${pushed_blob_repo[$digest]:-}" ] && continue
if [ -n "${claimed[$digest]:-}" ]; then
conflict=1
break
fi
done < <(manifest_blob_digests "${ref_manifest[$img]}")
if [ "$conflict" -eq 0 ]; then
wave+=("$img")
while IFS= read -r digest; do
[ -n "$digest" ] && claimed["$digest"]=1
done < <(manifest_blob_digests "${ref_manifest[$img]}")
else
deferred+=("$img")
fi
done
if [ ${#wave[@]} -eq 0 ]; then
wave=("${remaining[0]}")
deferred=("${remaining[@]:1}")
fi
echo "Copying images (batch $wave_no): ${wave[*]}" >> "$LOG_FILE" 2>&1
launch_pool copy_verified_image copy "$jobs" "" "${wave[@]}"
pool_collect copy "${wave[@]}" || exit 1
for img in "${wave[@]}"; do
record_shared_blobs "$img" "${ref_manifest[$img]}" pushed_blob_repo
done
remaining=("${deferred[@]}")
done
launch_pool pull_verified_image pull "$jobs" "" "${TRUSTED_CONTAINERS[@]}"
pool_collect pull "${TRUSTED_CONTAINERS[@]}" || exit 1
}
+2 -1
View File
@@ -11,7 +11,8 @@
{% set DATA_RETENTION_METHOD = ELASTICSEARCHMERGED.data_retention_method %}
{% set PILLAR_GLOBAL_OVERRIDES = {} %}
{% set ES_INDEX_PILLAR = salt['pillar.get']('elasticsearch:index_settings', {}) %}
{# merge into a copy: pillar.get returns a live reference and this map pops/updates ES_INDEX_PILLAR #}
{% set ES_INDEX_PILLAR = salt['defaults.merge'](salt['pillar.get']('elasticsearch:index_settings', {}), {}, in_place=False) %}
{% if ES_INDEX_PILLAR.global_overrides is defined %}
{% set PILLAR_GLOBAL_OVERRIDES = ES_INDEX_PILLAR.pop('global_overrides') %}
{% endif %}
-19
View File
@@ -17,7 +17,6 @@ is older than debounce_seconds, this script:
* concatenates the actions lists from every ready intent
* dedupes by (state or __highstate__, tgt, tgt_type)
* drops actions whose target matches no accepted minion (e.g. a role with no nodes yet)
* holds everything for a later pass while salt-master has only just started
* dispatches a single `salt-run state.orchestrate orch.push_batch --async`
with the deduped actions list passed as pillar kwargs
* deletes the contributed intent files on successful dispatch
@@ -47,12 +46,6 @@ PENDING_DIR = '/opt/so/state/push_pending'
LOCK_FILE = os.path.join(PENDING_DIR, '.lock')
LOG_FILE = '/opt/so/log/salt/so-push-drainer.log'
MASTER_CONFIG = '/etc/salt/master'
MASTER_PIDFILE = '/var/run/salt-master.pid'
# Minions rejoin a restarted master's publisher up to ~22s after it returns (zmq reconnect interval
# plus jitter, each up to recon_default + recon_max) and a job published before then reaches nobody.
# Doubled to allow for a slow master start.
MASTER_SETTLE_SECONDS = 45
DISPATCHED_DIR = '/opt/so/state/push_dispatched'
@@ -147,14 +140,6 @@ def _targeted(actions, log):
return targeted
def _master_settling(now):
try:
age = now - os.path.getmtime(MASTER_PIDFILE)
except OSError:
return False
return 0 <= age < MASTER_SETTLE_SECONDS
def _dispatch(actions, log):
pillar_arg = json.dumps({'actions': actions})
cmd = [
@@ -425,10 +410,6 @@ def main():
log.debug('no ready intents (%d still in debounce window)', skipped)
return 0
if _master_settling(now):
log.info('salt-master just started; holding %d intent(s) until minions reconnect', len(ready))
return 0
combined_actions = []
oldest_first_touch = now
all_paths = []
@@ -199,17 +199,6 @@ class TestHelpers(DrainerTestCase):
drainer._unlink(self.tmpdir, self.log)
self.log.exception.assert_called_once()
def test_master_settling(self):
pidfile = os.path.join(self.tmpdir, 'salt-master.pid')
now = time.time()
with patch.object(drainer, 'MASTER_PIDFILE', pidfile):
self.assertFalse(drainer._master_settling(now))
self.write_json(self.tmpdir, 'salt-master.pid', '1100')
for age, settling in ((0, True), (drainer.MASTER_SETTLE_SECONDS - 1, True),
(drainer.MASTER_SETTLE_SECONDS, False), (-60, False)):
os.utime(pidfile, (now - age, now - age))
self.assertIs(drainer._master_settling(now), settling, age)
class TestDispatch(DrainerTestCase):
@@ -486,7 +475,6 @@ class TestMain(DrainerTestCase):
('_load_push_cfg', {'side_effect': lambda: self.cfg}),
('_check_dispatched', {}),
('_targeted', {'side_effect': lambda actions, log: actions}),
('_master_settling', {'return_value': False}),
):
patcher = patch.object(drainer, name, **kwargs)
setattr(self, name, patcher.start())
@@ -540,16 +528,6 @@ class TestMain(DrainerTestCase):
with patch.object(drainer.os, 'unlink', side_effect=OSError('busy')):
self.assertEqual(drainer.main(), 0)
def test_holds_while_master_settling(self):
path = self.intent('pillar_soc.json')
self._master_settling.return_value = True
with patch.object(drainer, '_dispatch') as dispatch:
self.assertEqual(drainer.main(), 0)
dispatch.assert_not_called()
self._check_dispatched.assert_called_once()
self.assertTrue(os.path.exists(path))
self.assertIn('holding 1 intent(s)', self.logged('info'))
def test_dispatch_failure_keeps_intents(self):
path = self.intent('pillar_soc.json')
with patch.object(drainer, '_dispatch', return_value=None):
+6 -13
View File
@@ -4,19 +4,8 @@
{% set BATCH_WAIT = AUTOAPPLY.batch_wait %}
{# queue must be a top-level salt.state arg (kwarg is ignored); an int is max_queue and still fails on conflict #}
{# refresh_pillar doubles as the reachability check: minions take up to ~22s to rejoin a restarted master's
publisher, and a job published before then reaches nobody. Each failed attempt takes ~15s to time out. #}
{% for action in actions %}
refresh_pillar_{{ loop.index }}:
salt.function:
- name: saltutil.refresh_pillar
- tgt: '{{ action.tgt }}'
- tgt_type: {{ action.get('tgt_type', 'compound') }}
- retry:
attempts: 3
interval: 10
{% if action.get('highstate') %}
apply_highstate_{{ loop.index }}:
salt.state:
@@ -26,9 +15,13 @@ apply_highstate_{{ loop.index }}:
- batch: {{ action.get('batch', BATCH) }}
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
- queue: True
- require:
- salt: refresh_pillar_{{ loop.index }}
{% else %}
refresh_pillar_{{ loop.index }}:
salt.function:
- name: saltutil.refresh_pillar
- tgt: '{{ action.tgt }}'
- tgt_type: {{ action.get('tgt_type', 'compound') }}
apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
salt.state:
- tgt: '{{ action.tgt }}'