#!/usr/bin/env bash # A fake docker client for PipelineTests: .gitea/scripts/pulizia-docker.sh runs against a small daemon written in text # files, and the test reads what is left. No daemon, no network. It models only what the cleanup relies on, the way # Docker does it: # - filters of «ps»: label filters must all match, the values of any other key are alternatives (status, name as a # regular expression, ancestor by name or id, volume and network by name; stopped containers too); # - «rm» refuses a running container without -f; # - «image rm » only untags when the image has other names, and refuses an image a container uses (always if the # container runs, without -f if it is stopped); # - «image prune» takes only images no container uses, running or stopped: without -a only those without a name, with # -a any; «until» keeps those created in the last 72 or 24 hours. With -a an image a container uses stays but loses # its extra names, as moby does it with the classic store or, with $FAKE_DOCKER_WORLD/store, with containerd; # - «builder prune» only answers (the cache is not modelled); # - «volume rm» refuses a volume a container mounts, running or stopped, even with -f; # - «network rm» refuses the predefined networks and a network a running container is attached to; # - creation times: containers and images in UTC with nanoseconds, volumes and networks two hours ahead with the # offset (+02:00), as a daemon in Italy writes them; the Created of a network is a time of Go, which the template # prints as «2026-10-21 06:17:03.123456789 +0200 CEST» and {{json .Created}} as RFC 3339 between quotes. # Any other call is an error (exit 3), so the test sees every command the cleanup starts to use. That includes any prune # other than those the cleanup may run: image prune -f [--filter until=72h], image prune -a -f --filter until=24h, # builder prune [-a] -f --filter until=24h. # # $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels|volumes|networks # (labels as Docker gives them to the container: those of the image plus those of «run»; # volumes and networks by name, comma separated; the last fields may be missing) # $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels|size # $FAKE_DOCKER_WORLD/volumes name|minutes ago (missing: just created) # $FAKE_DOCKER_WORLD/networks id|name|minutes ago # $FAKE_DOCKER_WORLD/store optional: «containerd» for the containerd image store (what «docker info» says); # otherwise the classic store of overlay2 # $FAKE_DOCKER_WORLD/broken optional: commands («image prune», «builder prune») that fail as if the daemon refused # $FAKE_DOCKER_WORLD/calls every call, one per line (written here), after BUILDX_BUILDER= when it is set set -uo pipefail world="${FAKE_DOCKER_WORLD:?}" printf '%sdocker %s\n' "${BUILDX_BUILDER:+BUILDX_BUILDER=$BUILDX_BUILDER }" "$*" >> "$world/calls" now=$(date -u +%s) touch "$world/containers" "$world/images" "$world/volumes" "$world/networks" unexpected() { echo "fake docker: unexpected call: $*" >&2 exit 3 } broken() { [[ -f "$world/broken" ]] && grep -qxF -- "$1" "$world/broken" } created() { date -u -d "@$((now - $1 * 60))" +%Y-%m-%dT%H:%M:%S.123456789Z; } created_in_italy() { date -u -d "@$((now - ${1:-0} * 60 + 7200))" "+%Y-%m-%dT%H:%M:%S${2:-}+02:00"; } # The value of a label, or $3 when it is missing («docker ps» prints nothing, «inspect» prints ). label_value() { local labels=",$1," key="$2" rest [[ "$labels" == *",$key="* ]] || { echo "${3:-}"; return; } rest="${labels#*,"$key"=}" echo "${rest%%,*}" } has_label() { local labels=",$1," want="$2" if [[ "$want" == *=* ]]; then [[ "$labels" == *",$want,"* ]] else [[ "$labels" == *",$want="* ]] fi } # Image id for a name or an id; empty when there is none. resolve_image() { local ref="$1" id names rest while IFS='|' read -r id names rest; do [[ -n "$id" ]] || continue if [[ "$id" == "$ref" || ",$names," == *",$ref,"* ]]; then echo "$id" return fi done < "$world/images" } # The line of a world file whose first field (or, with $3, whose field number $3) is $2; empty when there is none. line_of() { local file="$1" wanted="$2" field="${3:-1}" line fields while IFS= read -r line; do [[ -n "$line" ]] || continue IFS='|' read -r -a fields <<< "$line" if [[ "${fields[0]}" == "$wanted" || "${fields[field - 1]:-}" == "$wanted" ]]; then echo "$line" return fi done < "$file" } image_line() { line_of "$world/images" "$1"; } # The container line for an id or a name; empty when there is none. find_container() { line_of "$world/containers" "$1" 2; } volume_line() { line_of "$world/volumes" "$1"; } # The network line for an id or a name; empty when there is none. network_line() { line_of "$world/networks" "$1" 2; } # Rewrites a world file without the lines whose first field is $2. drop() { local file="$1" id="$2" line : > "$file.new" while IFS= read -r line; do [[ "${line%%|*}" == "$id" ]] || printf '%s\n' "$line" >> "$file.new" done < "$file" mv "$file.new" "$file" } # True when a container uses the image (any: in any state; running: only a running one). used_by() { local image="$1" want="$2" id name state age config image_id labels volumes networks while IFS='|' read -r id name state age config image_id labels volumes networks; do [[ -n "$id" && "$image_id" == "$image" ]] || continue [[ "$want" == any || "$state" == running ]] && return 0 done < "$world/containers" return 1 } # True when a container (any: in any state; running: only a running one) has the volume or the network. uses() { local field="$1" wanted="$2" want="$3" id name state age config image_id labels volumes networks list while IFS='|' read -r id name state age config image_id labels volumes networks; do [[ -n "$id" ]] || continue if [[ "$field" == volume ]]; then list="$volumes"; else list="$networks"; fi [[ ",$list," == *",$wanted,"* ]] || continue [[ "$want" == any || "$state" == running ]] && return 0 done < "$world/containers" return 1 } matches() { local name="$1" state="$2" image_id="$3" labels="$4" volumes="$5" networks="$6" shift 6 local -A seen=() ok=() local filter key value for filter in "$@"; do key="${filter%%=*}" value="${filter#*=}" case "$key" in label) has_label "$labels" "$value" || return 1 ;; status) seen[$key]=1; [[ "$state" == "$value" ]] && ok[$key]=1 ;; name) seen[$key]=1; [[ "$name" =~ $value ]] && ok[$key]=1 ;; ancestor) seen[$key]=1; [[ -n "$image_id" && "$(resolve_image "$value")" == "$image_id" ]] && ok[$key]=1 ;; volume) seen[$key]=1; [[ ",$volumes," == *",$value,"* ]] && ok[$key]=1 ;; network) seen[$key]=1; [[ ",$networks," == *",$value,"* ]] && ok[$key]=1 ;; *) unexpected "filter $filter" ;; esac done for key in "${!seen[@]}"; do [[ -n "${ok[$key]:-}" ]] || return 1 done return 0 } ps_command() { local quiet=0 format='{{.ID}} {{.Names}}' filters=() while (($#)); do case "$1" in -a | --no-trunc) ;; -q) quiet=1 ;; --filter) filters+=("$2"); shift ;; --format) format="$2"; shift ;; *) unexpected "ps $1" ;; esac shift done local id name state age config image_id labels volumes networks out key while IFS='|' read -r id name state age config image_id labels volumes networks; do [[ -n "$id" ]] || continue matches "$name" "$state" "$image_id" "$labels" "$volumes" "$networks" "${filters[@]}" || continue if ((quiet)); then echo "$id" continue fi out="${format//"{{.ID}}"/$id}" out="${out//"{{.Names}}"/$name}" while [[ "$out" =~ \{\{\.Label\ \"([^\"]+)\"\}\} ]]; do key="${BASH_REMATCH[1]}" out="${out/"${BASH_REMATCH[0]}"/$(label_value "$labels" "$key" "")}" done [[ "$out" == *"{{"* ]] && unexpected "ps --format $format" printf '%s\n' "$out" done < "$world/containers" return 0 } container_inspect() { local format="" [[ "${1:-}" == -f ]] && { format="$2"; shift 2; } (($#)) || unexpected "container inspect without a container" local ref line id name state age config image_id labels volumes networks status=0 for ref in "$@"; do line=$(find_container "$ref") if [[ -z "$line" ]]; then echo "Error: No such container: $ref" >&2 status=1 continue fi IFS='|' read -r id name state age config image_id labels volumes networks <<< "$line" case "$format" in "") echo "[{\"Id\": \"$id\"}]" ;; "{{.Created}}") created "$age" ;; "{{.Config.Image}}") echo "$config" ;; "{{.Image}}") echo "$image_id" ;; "{{.Image}} {{.Config.Image}}") echo "$image_id $config" ;; "{{.Name}}") echo "/$name" ;; '{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "" ;; *) unexpected "container inspect -f $format" ;; esac done return "$status" } rm_command() { local force=0 while [[ "${1:-}" == -* ]]; do case "$1" in -f) force=1 ;; -v) ;; *) unexpected "rm $1" ;; esac shift done local line id name state rest line=$(find_container "${1:?}") [[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; } IFS='|' read -r id name state rest <<< "$line" if [[ "$state" == running && "$force" == 0 ]]; then echo "Error: cannot remove container \"/$name\": container is running: stop the container before removing or force remove" >&2 exit 1 fi drop "$world/containers" "$id" } image_ls() { local format="" reference="" while (($#)); do case "$1" in --no-trunc) ;; --filter) [[ "$2" == reference=* ]] || unexpected "image ls --filter $2"; reference="${2#reference=}"; shift ;; --format) format="$2"; shift ;; *) unexpected "image ls $1" ;; esac shift done [[ -n "$format" ]] || unexpected "image ls without --format" local id names age labels size tag out while IFS='|' read -r id names age labels size; do [[ -n "$id" ]] || continue tags=() [[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names" if ((${#tags[@]} == 0)); then [[ -z "$reference" ]] || continue tags=(":") fi for tag in "${tags[@]}"; do [[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] || continue out="${format//"{{.ID}}"/$id}" out="${out//"{{.Repository}}"/${tag%:*}}" out="${out//"{{.Tag}}"/${tag##*:}}" out="${out//"{{.Size}}"/${size:-100MB}}" [[ "$out" == *"{{"* ]] && unexpected "image ls --format $format" printf '%s\n' "$out" done done < "$world/images" return 0 } image_inspect() { local format="" [[ "${1:-}" == -f ]] && { format="$2"; shift 2; } local wanted id names age labels size wanted=$(resolve_image "${1:?}") [[ -n "$wanted" ]] || { echo "Error: No such image: $1" >&2; exit 1; } IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")" case "$format" in "") echo "[{\"Id\": \"$id\"}]" ;; "{{.Created}}") created "$age" ;; "{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;; *) unexpected "image inspect -f $format" ;; esac } image_rm() { local force=0 [[ "${1:-}" == -f ]] && { force=1; shift; } local ref="${1:?}" wanted id names age labels size left="" tag wanted=$(resolve_image "$ref") [[ -n "$wanted" ]] || { echo "Error: No such image: $ref" >&2; exit 1; } IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")" tags=() [[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names" if [[ "$ref" != "$id" && ${#tags[@]} -gt 1 ]]; then for tag in "${tags[@]}"; do [[ "$tag" == "$ref" ]] || left="${left:+$left,}$tag"; done drop "$world/images" "$id" printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images" echo "Untagged: $ref" return 0 fi if [[ "$ref" == "$id" && ${#tags[@]} -gt 1 && "$force" == 0 ]]; then echo "Error: conflict: unable to delete $id (must be forced) - image is referenced in multiple repositories" >&2 exit 1 fi if used_by "$id" running || { [[ "$force" == 0 ]] && used_by "$id" any; }; then echo "Error: conflict: unable to remove repository reference \"$ref\" - container is using its referenced image" >&2 exit 1 fi drop "$world/images" "$id" echo "Deleted: $id" } # The full name of an image name, the way Docker sorts references: docker.io/library/ or docker.io/ before the names # of Docker Hub written without a domain, :latest when the tag is missing. full_name() { local name="$1" first [[ "${name##*/}" == *:* ]] || name="$name:latest" if [[ "$name" != */* ]]; then echo "docker.io/library/$name" return fi first="${name%%/*}" if [[ "$first" == *.* || "$first" == *:* || "$first" == localhost ]]; then echo "$name"; else echo "docker.io/$name"; fi } # The names «image prune -a» leaves to an image a container uses, comma separated, the way moby does it. With the # classic store it removes the references in lexical order of their full names and only the last one is refused # (ImageDelete keeps the single reference of an image in use); with containerd it keeps the names the containers were # created from and, when a container uses the image by id and no name would be left, the last one in lexical order. names_kept() { local image="$1" names="$2" sorted name full cid cname state age config image_id rest by_id=0 local -A from=() local kept=() sorted=$(IFS=','; for name in $names; do printf '%s %s\n' "$(full_name "$name")" "$name"; done | LC_ALL=C sort) if [[ "$(store)" == classic ]]; then tail -n 1 <<< "$sorted" | cut -d' ' -f2- return fi while IFS='|' read -r cid cname state age config image_id rest; do [[ -n "$cid" && "$image_id" == "$image" ]] || continue if [[ "$config" == "$image" ]]; then by_id=1; else from[$(full_name "$config")]=1; fi done < "$world/containers" while read -r full name; do [[ -n "${from[$full]:-}" ]] && kept+=("$name") done <<< "$sorted" ((${#kept[@]} > 0 || !by_id)) || kept=("$(tail -n 1 <<< "$sorted" | cut -d' ' -f2-)") (IFS=','; echo "${kept[*]}") } image_prune() { local all=0 hours=0 case "$*" in "-f") ;; "-f --filter until=72h") hours=72 ;; "-a -f --filter until=24h") all=1; hours=24 ;; *) unexpected "image prune $*" ;; esac broken "image prune" && { echo "Error response from daemon: a prune operation is already running" >&2; exit 1; } local id names age labels size gone=() untag=() tag left while IFS='|' read -r id names age labels size; do [[ -n "$id" ]] || continue ((all)) || [[ -z "$names" ]] || continue ((age >= hours * 60)) || continue if used_by "$id" any; then [[ "$names" == *,* ]] && untag+=("$id") else gone+=("$id") fi done < "$world/images" ((${#gone[@]} + ${#untag[@]} == 0)) || echo "Deleted Images:" for id in "${untag[@]}"; do IFS='|' read -r id names age labels size <<< "$(image_line "$id")" left=$(names_kept "$id" "$names") IFS=',' read -r -a tags <<< "$names" for tag in "${tags[@]}"; do [[ ",$left," == *",$tag,"* ]] || echo "untagged: $tag" done drop "$world/images" "$id" printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images" done for id in "${gone[@]}"; do IFS='|' read -r id names age labels size <<< "$(image_line "$id")" tags=() [[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names" for tag in "${tags[@]}"; do echo "untagged: $tag" echo "untagged: ${tag%:*}@sha256:0123456789abcdef" done drop "$world/images" "$id" echo "deleted: sha256:$id" done echo if ((${#gone[@]} > 0)); then echo "Total reclaimed space: ${#gone[@]}00MB" else echo "Total reclaimed space: 0B" fi } builder_prune() { case "$*" in "-f --filter until=24h" | "-a -f --filter until=24h") ;; *) unexpected "builder prune $*" ;; esac broken "builder prune" && { echo "ERROR: failed to prune build cache: a prune operation is already running" >&2; exit 1; } printf 'Total:\t1.5GB\n' } volume_ls() { local filters=() format='{{.Name}}' filter name age while (($#)); do case "$1" in -q) ;; --filter) filters+=("$2"); shift ;; --format) format="$2"; shift ;; *) unexpected "volume ls $1" ;; esac shift done [[ "$format" == '{{.Name}}' ]] || unexpected "volume ls --format $format" while IFS='|' read -r name age; do [[ -n "$name" ]] || continue for filter in "${filters[@]}"; do case "$filter" in name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;; dangling=true) uses volume "$name" any && continue 2 ;; *) unexpected "volume ls --filter $filter" ;; esac done echo "$name" done < "$world/volumes" return 0 } volume_inspect() { local format="" [[ "${1:-}" == -f ]] && { format="$2"; shift 2; } local line name age line=$(volume_line "${1:?}") [[ -n "$line" ]] || { echo "Error response from daemon: get $1: no such volume" >&2; exit 1; } IFS='|' read -r name age <<< "$line" case "$format" in "") echo "[{\"Name\": \"$name\"}]" ;; "{{.CreatedAt}}") created_in_italy "$age" ;; *) unexpected "volume inspect -f $format" ;; esac } volume_rm() { [[ "${1:-}" == -f ]] && shift local name="${1:?}" [[ -n "$(volume_line "$name")" ]] || { echo "Error response from daemon: get $name: no such volume" >&2; exit 1; } if uses volume "$name" any; then echo "Error response from daemon: remove $name: volume is in use" >&2 exit 1 fi drop "$world/volumes" "$name" } network_ls() { local filters=() format='{{.ID}} {{.Name}}' filter id name age while (($#)); do case "$1" in --no-trunc) ;; --filter) filters+=("$2"); shift ;; --format) format="$2"; shift ;; *) unexpected "network ls $1" ;; esac shift done [[ "$format" == '{{.ID}} {{.Name}}' ]] || unexpected "network ls --format $format" while IFS='|' read -r id name age; do [[ -n "$id" ]] || continue for filter in "${filters[@]}"; do case "$filter" in name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;; *) unexpected "network ls --filter $filter" ;; esac done echo "$id $name" done < "$world/networks" return 0 } network_inspect() { local format="" [[ "${1:-}" == -f ]] && { format="$2"; shift 2; } local line id name age line=$(network_line "${1:?}") [[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; } IFS='|' read -r id name age <<< "$line" case "$format" in "") echo "[{\"Id\": \"$id\", \"Name\": \"$name\"}]" ;; "{{json .Created}}") echo "\"$(created_in_italy "$age" .123456789)\"" ;; # Created of a network is a time.Time: the template prints it the way Go does, not as RFC 3339. "{{.Created}}") date -u -d "@$((now - ${age:-0} * 60 + 7200))" "+%Y-%m-%d %H:%M:%S.123456789 +0200 CEST" ;; *) unexpected "network inspect -f $format" ;; esac } network_rm() { local line id name age line=$(network_line "${1:?}") [[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; } IFS='|' read -r id name age <<< "$line" case "$name" in bridge | host | none) echo "Error response from daemon: $name is a pre-defined network and cannot be removed" >&2; exit 1 ;; esac if uses network "$name" running; then echo "Error response from daemon: error while removing network: network $name id $id has active endpoints" >&2 exit 1 fi drop "$world/networks" "$id" } store() { if [[ "$(cat "$world/store" 2> /dev/null)" == containerd ]]; then echo containerd; else echo classic; fi } # The DriverStatus of «docker info» as Docker prints it: with the containerd image store the snapshotter, with the # classic one the details of overlay2. info_command() { [[ "$*" == "--format {{json .DriverStatus}}" ]] || unexpected "info $*" if [[ "$(store)" == containerd ]]; then echo '[["driver-type","io.containerd.snapshotter.v1"]]' else echo '[["Backing Filesystem","extfs"],["Supports d_type","true"],["Using metacopy","false"],["Native Overlay Diff","true"],["userxattr","false"]]' fi } system_df() { case "$*" in "") echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;; "--format {{.Type}}|{{.Size}}|{{.Reclaimable}}") printf '%s\n' "Images|9.1GB|6.2GB (68%)" "Containers|120MB|80MB (66%)" "Local Volumes|3.4GB|1.1GB (32%)" "Build Cache|5.3GB|4.8GB" ;; *) unexpected "system df $*" ;; esac } case "${1:-}" in ps) shift; ps_command "$@" ;; container) [[ "${2:-}" == inspect ]] || unexpected "$*"; shift 2; container_inspect "$@" ;; rm) shift; rm_command "$@" ;; image) sub="${2:-}" shift 2 case "$sub" in ls) image_ls "$@" ;; inspect) image_inspect "$@" ;; rm) image_rm "$@" ;; prune) image_prune "$@" ;; *) unexpected "image $sub" ;; esac ;; builder) [[ "${2:-}" == prune ]] || unexpected "$*"; shift 2; builder_prune "$@" ;; buildx) [[ "${2:-}" == rm ]] || unexpected "$*"; echo "ERROR: no builder \"${4:-}\" found" >&2; exit 1 ;; volume) sub="${2:-}" shift 2 case "$sub" in ls) volume_ls "$@" ;; inspect) volume_inspect "$@" ;; rm) volume_rm "$@" ;; *) unexpected "volume $sub" ;; esac ;; network) sub="${2:-}" shift 2 case "$sub" in ls) network_ls "$@" ;; inspect) network_inspect "$@" ;; rm) network_rm "$@" ;; *) unexpected "network $sub" ;; esac ;; system) [[ "${2:-}" == df ]] || unexpected "$*"; shift 2; system_df "$@" ;; info) shift; info_command "$@" ;; *) unexpected "$*" ;; esac