diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..28cb307 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +messages.jsonl + diff --git a/README.md b/README.md index 6c8471e..3cbdfd9 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,50 @@ # ACR Cold Archive Worker -Archives private Azure Container Registry images into `docker load` compatible `.tar.gz` blobs and uploads them to Azure Blob Storage Archive tier. +Archives private Azure Container Registry (ACR) images into `docker load`-compatible `.tar.gz` files and uploads them to Azure Blob Storage Archive tier. -## Flow +This project is designed to run as an **Azure Container Apps Job** triggered by **Azure Queue Storage** backlog. Each execution processes exactly one image. -1. Read one queue message -2. Authenticate with managed identity -3. Get ACR token with `az acr login --expose-token` -4. Export image to docker archive tar with `skopeo` -5. Compress with `pigz` -6. Upload `.tar.gz` -7. Upload sidecar manifest `.json` +## Assumptions -## Queue message +This repo assumes all of the following already exist: + +* An **Azure Container Apps managed environment** in the target resource group. +* A **storage account** that will be used for: + + * the queue of work items, + * the blob container that stores archives and manifests, + * the Azure Files share used as scratch space. +* An **Azure Queue Storage queue** for work items. +* An **Azure Blob container** for archive output. +* An **Azure Files share** mounted into the ACA Job as scratch storage. +* A source **Azure Container Registry** containing the images to archive. +* A deployable worker image published to a registry that ACA can pull from. + +This worker also assumes: + +* Queue messages are JSON with explicit destination naming. +* Each message includes a fully qualified image reference with an explicit tag. +* The output artifact must remain `docker load` compatible. +* Scratch storage is required because the current implementation writes a temporary uncompressed `docker-archive` tar before gzip compression. + +## Current Design + +For each queue message, the worker: + +1. Logs into Azure using managed identity. +2. Claims exactly one queue message using a visibility timeout. +3. Reads the source image reference and output blob name from the message. +4. Authenticates to ACR using `az acr login --expose-token`. +5. Inspects the image with `skopeo` to capture digest metadata. +6. Copies the image to `docker-archive` format. +7. Compresses the archive with `pigz`. +8. Uploads the `.tar.gz` to Blob Storage. +9. Uploads a sidecar manifest JSON. +10. Deletes the queue message only after successful uploads. + +If the worker crashes before deleting the queue message, Azure Queue Storage makes the message visible again after the visibility timeout expires. + +## Queue Message Format ```json { @@ -20,9 +52,255 @@ Archives private Azure Container Registry images into `docker load` compatible ` "blobContainer": "images", "blobBaseName": "hello-pacta--latest.tar.gz" } +``` + +Notes: + +* `image` must include an explicit tag. +* `blobBaseName` intentionally uses `--` instead of `:`. +* This message produces: + + * `images/hello-pacta--latest.tar.gz` + * `images/hello-pacta--latest.tar.gz.json` + +## Manifest Format + +Example sidecar manifest: + +```json +{ + "image": "transitionmonitordockerregistry.azurecr.io/hello-pacta:latest", + "archiveBlob": "images/hello-pacta--latest.tar.gz", + "createdAtUtc": "2026-04-08T12:34:56Z", + "mediaType": "docker-archive+gzip", + "compression": { + "format": "gzip", + "level": 1 + }, + "source": { + "registry": "transitionmonitordockerregistry.azurecr.io", + "repository": "hello-pacta", + "tag": "latest", + "digest": "sha256:..." + } +} +``` + +## Required Environment Variables + +### Core + +```bash +STORAGE_ACCOUNT= +SCRATCH_DIR=/mnt/scratch +PIGZ_LEVEL=1 +AZURE_STORAGE_AUTH_MODE=login +``` + +### Queue Mode + +```bash +QUEUE_ACCOUNT= +QUEUE_NAME= +QUEUE_VISIBILITY_TIMEOUT_SECONDS=3600 +``` + +### Optional + +```bash +AZURE_CLIENT_ID= +``` + +If `AZURE_CLIENT_ID` is omitted, the worker uses the job's system-assigned managed identity. + +## Azure Permissions and Authentication + +This project supports two authentication models for ACR: + +### Option 1: Managed Identity (recommended default) + +* Assign the ACA Job identity: + + * `AcrPull` on the source ACR +* The worker uses: + + ```bash + az acr login --expose-token + ``` + +### Option 2: ACR Token (your current setup) + +If you are using an ACR **token + password**, you do not need RBAC on the registry. + +Instead, pass credentials to the worker and use them with `skopeo`. + +Required environment variables: + +```bash +ACR_USERNAME= +ACR_PASSWORD= +``` + +And the worker should use: + +```bash +--src-creds "$ACR_USERNAME:$ACR_PASSWORD" +``` + +Notes: + +* This bypasses `az acr login --expose-token` +* Useful when you want scoped access without granting RBAC +* Recommended for tightly controlled, read-only access + +### Storage Access (always via Managed Identity) + +Regardless of ACR auth method, storage access still uses managed identity: + +Required roles on the storage account: + +* `Storage Queue Data Contributor` +* `Storage Blob Data Contributor` + +--- + +## Important Limitation: Azure Files Mounts + +Azure Container Apps supports mounting Azure Files into the environment, but **the storage registration currently requires a storage account key**. Microsoft explicitly states that Container Apps **does not support identity-based access to Azure file shares** for this mount path. If key access is disabled on your storage account, the Azure Files mount cannot be configured the normal ACA way. + +That means your current storage settings create a blocker for the scratch mount approach. + +## Startup Instructions + +### 1. Build and publish the worker image + +Example: + +```bash +docker build -t ghcr.io/rmi/workflow-acr-cold-archive:pr-2 . +docker push ghcr.io/rmi/workflow-acr-cold-archive:pr-2 +``` + +### 2. Create the storage resources if they do not already exist + +You need: + +* queue: `docker-transfer` +* blob container: `images` +* Azure Files share: `transfer-scratch` + +### 3. Deploy the ACA Job + +The deployment template needs these values: + +* `containerAppsEnvironmentResourceId` +* `image` +* `storageAccountName` +* `queueName` +* `fileShareName` +* image registry settings if the worker image is private + +Your current values are: + +* environment: `pacta-test` +* image: `ghcr.io/rmi/workflow-acr-cold-archive:pr-2` +* storage account: `pactadockerimages` +* queue: `docker-transfer` +* fileshare: `transfer-scratch` + +### 4. Assign managed identity permissions + +After the ACA Job exists, grant its identity access to: + +* source ACR: `AcrPull` +* storage account: `Storage Queue Data Contributor` +* storage account: `Storage Blob Data Contributor` + +### 5. Enqueue a test message + +Example: + +```json +{ + "image": "transitionmonitordockerregistry.azurecr.io/hello-pacta:latest", + "blobContainer": "images", + "blobBaseName": "hello-pacta--latest.tar.gz" +} +``` + +### 6. Watch job executions and logs + +Confirm that: + +* one execution claims one message, +* the worker uploads `.tar.gz`, +* the worker uploads `.json`, +* the queue message is deleted only after success. + +## Local Testing + +Local file-mode testing is still supported with: + +```bash +export STORAGE_ACCOUNT= +export QUEUE_MESSAGE_FILE=examples/message.json +./archive_worker.sh +``` + +But cloud-first testing is the preferred path for this project. + +## Restore Workflow + +```bash +docker load < hello-pacta--latest.tar.gz +``` + +## Recommended Identity Choice + +For this job, start with a **system-assigned managed identity** on the ACA Job. + +Reasons: + +* It is the fastest path to get running. +* ACA Jobs support system-assigned and user-assigned identities. +* The same identity can be used for queue scaling and for the worker's Azure authentication. +* You do not need to create a separate identity resource unless you want to reuse the identity across multiple jobs or apps. + +Use a user-assigned identity later only if you want shared lifecycle or reuse across multiple resources. + +## Known Next Step + +Because your storage account currently has **key access disabled**, you will need to resolve scratch storage before the ACA deployment can mount Azure Files. The simplest options are: + +1. use a different storage account for the Azure Files scratch share where key-based mount is allowed, or +2. use another execution platform for the scratch-heavy step. + +Given ACA's current storage mount behavior, option 1 is the cleanest path if you want to keep ACA Jobs. + +## Deploy + +```bash +az deployment group create \ + --resource-group RMI-SP-PACTA-WEU-PAT-DEV \ + --template-file aca-job-deploy.bicep \ + --parameters \ + containerAppsEnvironmentResourceId='/subscriptions/feef729b-4584-44af-a0f9-4827075512f9/resourceGroups/RMI-SP-PACTA-WEU-PAT-DEV/providers/Microsoft.App/managedEnvironments/pacta-test' \ + image='ghcr.io/rmi/workflow-acr-cold-archive:pr-2' \ + useSystemAssignedIdentity=false \ + userAssignedIdentityResourceId='/subscriptions/feef729b-4584-44af-a0f9-4827075512f9/resourceGroups/RMI-SP-PACTA-WEU-PAT-DEV/providers/Microsoft.ManagedIdentity/userAssignedIdentities/docker-transfer' \ + storageAccountName='pactadockerimages' \ + fileShareName='docker-transfer-scratch' \ + storageAccountKey="$STORAGE_KEY" \ + queueName='docker-transfer' +``` + +### Queueing -## Required env vars -`STORAGE_ACCOUNT` -`SCRATCH_DIR` default /mnt/scratch -`PIGZ_LEVEL` default 1 -`AZURE_CLIENT_ID` optional for user-assigned identity +```bash +./prepare_acr_queue_messages.sh \ + --acr-name transitionmonitordockerregistry \ + --storage-account pactadockerimages \ + --queue-name docker-transfer \ + --blob-container images \ + --output-file messages.jsonl +``` diff --git a/archive_worker.sh b/archive_worker.sh index 9422847..3aa42d4 100644 --- a/archive_worker.sh +++ b/archive_worker.sh @@ -1,10 +1,15 @@ #!/usr/bin/env bash set -Eeuo pipefail -: "${QUEUE_MESSAGE_FILE:=/tmp/message.json}" : "${SCRATCH_DIR:=/mnt/scratch}" : "${PIGZ_LEVEL:=1}" : "${AZURE_STORAGE_AUTH_MODE:=login}" +: "${QUEUE_VISIBILITY_TIMEOUT_SECONDS:=3600}" +: "${QUEUE_MESSAGE_FILE:=}" +: "${VERBOSE:=1}" + +START_EPOCH="$(date +%s)" +LAST_STEP_EPOCH="$START_EPOCH" require_cmd() { command -v "$1" >/dev/null 2>&1 || { @@ -13,46 +18,143 @@ require_cmd() { } } +require_env() { + local name="$1" + if [[ -z "${!name:-}" ]]; then + echo "missing required env var: $name" >&2 + exit 2 + fi +} + require_cmd az require_cmd skopeo require_cmd pigz require_cmd jq require_cmd date +require_cmd base64 +require_cmd wc +require_cmd du log() { printf '[%s] %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$*" >&2 } +vlog() { + if [[ "$VERBOSE" == "1" ]]; then + log "$*" + fi +} + +step() { + local now elapsed total + now="$(date +%s)" + elapsed="$((now - LAST_STEP_EPOCH))" + total="$((now - START_EPOCH))" + LAST_STEP_EPOCH="$now" + log "STEP: $* | elapsed=${elapsed}s total=${total}s" +} + +on_error() { + local exit_code="$1" + local line_no="$2" + log "ERROR: exit_code=${exit_code} line=${line_no}" + if [[ -n "${MESSAGE_ID:-}" && -n "${QUEUE_NAME:-}" ]]; then + log "Queue message will remain undeleted and become visible again after timeout if not already expired" + fi +} +trap 'on_error $? $LINENO' ERR + +run_cmd() { + vlog "CMD: $*" + "$@" +} + login_azure() { + step "Logging into Azure" + export APPSETTING_WEBSITE_SITE_NAME=DUMMY if [[ -n "${AZURE_CLIENT_ID:-}" ]]; then - log "Logging into Azure with user-assigned managed identity" - az login --identity --username "$AZURE_CLIENT_ID" >/dev/null + log "Using user-assigned managed identity client_id=${AZURE_CLIENT_ID}" + run_cmd az login --identity --client-id "$AZURE_CLIENT_ID" >/dev/null else - log "Logging into Azure with system-assigned managed identity" - az login --identity >/dev/null + log "Using system-assigned managed identity" + run_cmd az login --identity >/dev/null fi } +queue_mode_enabled() { + [[ -n "${QUEUE_ACCOUNT:-}" && -n "${QUEUE_NAME:-}" ]] +} + +read_message_from_file() { + if [[ -z "$QUEUE_MESSAGE_FILE" ]]; then + echo "QUEUE_MESSAGE_FILE must be set when not using queue mode" >&2 + exit 2 + fi + step "Reading message from file" + MESSAGE_ID="local-file" + MESSAGE_JSON="$(cat "$QUEUE_MESSAGE_FILE")" + vlog "Loaded local message file ${QUEUE_MESSAGE_FILE}" +} + +read_message_from_queue() { + require_env QUEUE_ACCOUNT + require_env QUEUE_NAME + + step "Claiming one queue message" + log "Queue account=${QUEUE_ACCOUNT} queue=${QUEUE_NAME} visibility_timeout=${QUEUE_VISIBILITY_TIMEOUT_SECONDS}s" + + local raw + raw="$(az storage message get \ + --auth-mode "$AZURE_STORAGE_AUTH_MODE" \ + --account-name "$QUEUE_ACCOUNT" \ + --queue-name "$QUEUE_NAME" \ + --visibility-timeout "$QUEUE_VISIBILITY_TIMEOUT_SECONDS" \ + --num-messages 1 \ + --output json)" + + if [[ "$(jq 'length' <<<"$raw")" -eq 0 ]]; then + log "No queue messages available" + exit 0 + fi + + MESSAGE_ID="$(jq -r '.[0].id' <<<"$raw")" + POP_RECEIPT="$(jq -r '.[0].popReceipt' <<<"$raw")" + MESSAGE_TEXT_B64="$(jq -r '.[0].content' <<<"$raw")" + MESSAGE_JSON="$(printf '%s' "$MESSAGE_TEXT_B64" | base64 --decode)" + + log "Claimed queue message id=${MESSAGE_ID}" + vlog "Decoded message payload: ${MESSAGE_JSON}" +} + read_message() { - IMAGE_REF="$(jq -r '.image' "$QUEUE_MESSAGE_FILE")" - BLOB_CONTAINER="$(jq -r '.blobContainer' "$QUEUE_MESSAGE_FILE")" - BLOB_BASENAME="$(jq -r '.blobBaseName' "$QUEUE_MESSAGE_FILE")" + if queue_mode_enabled; then + read_message_from_queue + else + read_message_from_file + fi + + IMAGE_REF="$(jq -r '.image' <<<"$MESSAGE_JSON")" + BLOB_CONTAINER="$(jq -r '.blobContainer' <<<"$MESSAGE_JSON")" + BLOB_BASENAME="$(jq -r '.blobBaseName' <<<"$MESSAGE_JSON")" if [[ -z "$IMAGE_REF" || "$IMAGE_REF" == "null" ]]; then echo "queue message missing .image" >&2 - exit 2 + exit 2 fi if [[ -z "$BLOB_CONTAINER" || "$BLOB_CONTAINER" == "null" ]]; then echo "queue message missing .blobContainer" >&2 - exit 2 + exit 2 fi if [[ -z "$BLOB_BASENAME" || "$BLOB_BASENAME" == "null" ]]; then echo "queue message missing .blobBaseName" >&2 - exit 2 + exit 2 fi + + log "Resolved work item image=${IMAGE_REF} blob_container=${BLOB_CONTAINER} blob_name=${BLOB_BASENAME}" } parse_image_ref() { + step "Parsing image reference" LOGIN_SERVER="${IMAGE_REF%%/*}" REMAINDER="${IMAGE_REF#*/}" REPOSITORY="${REMAINDER%:*}" @@ -62,49 +164,90 @@ parse_image_ref() { echo "image must include explicit tag: $IMAGE_REF" >&2 exit 2 fi + + log "Parsed image login_server=${LOGIN_SERVER} repository=${REPOSITORY} tag=${TAG}" } get_acr_registry_name() { ACR_NAME="${LOGIN_SERVER%%.azurecr.io}" + vlog "Derived ACR name ${ACR_NAME} from login server ${LOGIN_SERVER}" } -get_acr_token() { - az acr login \ - --name "$ACR_NAME" \ - --expose-token \ - --output tsv \ - --query accessToken +resolve_registry_creds() { + step "Resolving registry credentials" + if [[ -n "${ACR_USERNAME:-}" && -n "${ACR_PASSWORD:-}" ]]; then + CREDS="${ACR_USERNAME}:${ACR_PASSWORD}" + log "Using explicit ACR token credentials for registry access" + else + log "Using Azure-managed auth to obtain ACR access token" + TOKEN="$(az acr login \ + --name "$ACR_NAME" \ + --expose-token \ + --output tsv \ + --query accessToken)" + CREDS="00000000-0000-0000-0000-000000000000:${TOKEN}" + fi } inspect_digest() { - skopeo inspect \ - --creds "00000000-0000-0000-0000-000000000000:${TOKEN}" \ + step "Inspecting image metadata" + run_cmd skopeo inspect \ + --creds "$CREDS" \ "docker://${IMAGE_REF}" > "${SCRATCH_DIR}/inspect.json" DIGEST="$(jq -r '.Digest' "${SCRATCH_DIR}/inspect.json")" + IMAGE_SIZE_BYTES="$(jq -r '.LayersData // [] | map(.Size // 0) | add // 0' "${SCRATCH_DIR}/inspect.json")" + log "Resolved image digest=${DIGEST} approx_layer_bytes=${IMAGE_SIZE_BYTES}" } make_paths() { + step "Preparing scratch paths" + mkdir -p "$SCRATCH_DIR" TAR_PATH="${SCRATCH_DIR}/image.tar" GZ_PATH="${SCRATCH_DIR}/${BLOB_BASENAME}" MANIFEST_PATH="${SCRATCH_DIR}/${BLOB_BASENAME}.json" + log "Scratch directory=${SCRATCH_DIR}" + vlog "Tar path=${TAR_PATH}" + vlog "Archive path=${GZ_PATH}" + vlog "Manifest path=${MANIFEST_PATH}" +} + +log_file_stats() { + local path="$1" + if [[ -f "$path" ]]; then + log "File stats path=${path} bytes=$(wc -c < "$path") disk=$(du -h "$path" | awk '{print $1}')" + fi } copy_and_compress() { rm -f "$TAR_PATH" "$GZ_PATH" "$MANIFEST_PATH" - log "Copying ${IMAGE_REF} to docker archive" - skopeo copy \ - --src-creds "00000000-0000-0000-0000-000000000000:${TOKEN}" \ + step "Copying image to docker archive" + run_cmd skopeo copy \ + --src-creds "$CREDS" \ "docker://${IMAGE_REF}" \ "docker-archive:${TAR_PATH}:${IMAGE_REF}" +log_file_stats "$TAR_PATH" + + step "Compressing archive with pigz" + run_cmd pigz -"${PIGZ_LEVEL}" -c "$TAR_PATH" > "$GZ_PATH" + log_file_stats "$GZ_PATH" + + if [[ -f "$TAR_PATH" && -f "$GZ_PATH" ]]; then + local tar_bytes gz_bytes + tar_bytes="$(wc -c < "$TAR_PATH")" + gz_bytes="$(wc -c < "$GZ_PATH")" + if [[ "$tar_bytes" -gt 0 ]]; then + log "Compression ratio original=${tar_bytes} compressed=${gz_bytes} percent=$(( gz_bytes * 100 / tar_bytes ))%" + fi + fi - log "Compressing archive" - pigz -"${PIGZ_LEVEL}" -c "$TAR_PATH" > "$GZ_PATH" rm -f "$TAR_PATH" + vlog "Removed temporary tar ${TAR_PATH}" } write_manifest() { + step "Writing manifest" CREATED_AT="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" ARCHIVE_BLOB="${BLOB_CONTAINER}/${BLOB_BASENAME}" @@ -133,49 +276,85 @@ write_manifest() { digest: $digest } }' > "$MANIFEST_PATH" + + log_file_stats "$MANIFEST_PATH" + vlog "Manifest contents: $(cat "$MANIFEST_PATH")" } upload_outputs() { - log "Uploading archive blob" - az storage blob upload \ + require_env STORAGE_ACCOUNT + + step "Uploading archive blob" + log "Uploading to account=${STORAGE_ACCOUNT} container=${BLOB_CONTAINER} name=${BLOB_BASENAME}" + run_cmd az storage blob upload \ --auth-mode "$AZURE_STORAGE_AUTH_MODE" \ --account-name "$STORAGE_ACCOUNT" \ --container-name "$BLOB_CONTAINER" \ --name "$BLOB_BASENAME" \ --file "$GZ_PATH" \ - --overwrite true \ - --tier Archive + --overwrite true >/dev/null - log "Uploading manifest blob" - az storage blob upload \ + step "Uploading manifest blob" + run_cmd az storage blob upload \ --auth-mode "$AZURE_STORAGE_AUTH_MODE" \ --account-name "$STORAGE_ACCOUNT" \ --container-name "$BLOB_CONTAINER" \ --name "${BLOB_BASENAME}.json" \ --file "$MANIFEST_PATH" \ - --overwrite true + --overwrite true >/dev/null +} + +delete_claimed_message() { + if ! queue_mode_enabled; then + return 0 + fi + + step "Deleting processed queue message" + log "Deleting queue message id=${MESSAGE_ID} from queue=${QUEUE_NAME}" + run_cmd az storage message delete \ + --auth-mode "$AZURE_STORAGE_AUTH_MODE" \ + --account-name "$QUEUE_ACCOUNT" \ + --queue-name "$QUEUE_NAME" \ + --id "$MESSAGE_ID" \ + --pop-receipt "$POP_RECEIPT" >/dev/null } cleanup() { + step "Cleaning scratch files" rm -f "$TAR_PATH" "$GZ_PATH" "$MANIFEST_PATH" "${SCRATCH_DIR}/inspect.json" } -main() { - mkdir -p "$SCRATCH_DIR" +print_startup_summary() { + log "Startup summary" + log " queue_mode=$(queue_mode_enabled && echo yes || echo no)" + log " scratch_dir=${SCRATCH_DIR}" + log " pigz_level=${PIGZ_LEVEL}" + log " storage_auth_mode=${AZURE_STORAGE_AUTH_MODE}" + log " queue_account=${QUEUE_ACCOUNT:-}" + log " queue_name=${QUEUE_NAME:-}" + log " queue_visibility_timeout_seconds=${QUEUE_VISIBILITY_TIMEOUT_SECONDS}" + log " storage_account=${STORAGE_ACCOUNT:-}" + log " queue_message_file=${QUEUE_MESSAGE_FILE:-}" + log " azure_client_id=${AZURE_CLIENT_ID:-system-assigned}" + log " acr_auth_mode=$([[ -n "${ACR_USERNAME:-}" && -n "${ACR_PASSWORD:-}" ]] && echo explicit-creds || echo azure-token)" +} +main() { + print_startup_summary login_azure read_message parse_image_ref get_acr_registry_name - TOKEN="$(get_acr_token)" - inspect_digest make_paths + resolve_registry_creds + inspect_digest copy_and_compress write_manifest upload_outputs + delete_claimed_message cleanup - - log "Completed ${IMAGE_REF}" + step "Completed successfully" + log "Finished image=${IMAGE_REF} total_runtime=$(( $(date +%s) - START_EPOCH ))s" } main "$@" diff --git a/prepare_acr_queue_messages.sh b/prepare_acr_queue_messages.sh new file mode 100755 index 0000000..b86f647 --- /dev/null +++ b/prepare_acr_queue_messages.sh @@ -0,0 +1,254 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +# Discover all ACR repos/tags and prepare queue messages for the cold-archive worker. +# +# Requirements: +# - az CLI logged in +# - jq +# +# Example dry run: +# ./prepare_acr_queue_messages.sh \ +# --acr-name transitionmonitordockerregistry \ +# --storage-account pactadockerimages \ +# --queue-name docker-transfer \ +# --blob-container images \ +# --output-file messages.jsonl +# +# Example enqueue: +# ./prepare_acr_queue_messages.sh \ +# --acr-name transitionmonitordockerregistry \ +# --storage-account pactadockerimages \ +# --queue-name docker-transfer \ +# --blob-container images \ +# --enqueue +# +# Optional ACR token auth: +# export ACR_USERNAME='...' +# export ACR_PASSWORD='...' +# +# Optional filters: +# --repo-prefix hello- +# --exclude-tag latest +# --include-untagged false + +VERBOSE="${VERBOSE:-1}" +ENQUEUE=0 +OUTPUT_FILE="" +BLOB_CONTAINER="images" +INCLUDE_UNTAGGED=0 +REPO_PREFIX="" +EXCLUDE_TAGS=() + +log() { + printf '[%s] %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$*" >&2 +} + +vlog() { + if [[ "${VERBOSE}" == "1" ]]; then + log "$*" + fi +} + +die() { + log "ERROR: $*" + exit 1 +} + +require_cmd() { + command -v "$1" >/dev/null 2>&1 || die "missing required command: $1" +} + +usage() { + cat <<'EOF' +Usage: + prepare_acr_queue_messages.sh + --acr-name NAME + --storage-account NAME + --queue-name NAME + [--blob-container NAME] + [--output-file PATH] + [--enqueue] + [--repo-prefix PREFIX] + [--exclude-tag TAG]... + [--include-untagged true|false] + +Notes: + - Without --enqueue, this writes JSONL output only. + - With --enqueue, this pushes each message to Azure Queue Storage. + - Queue message format: + {"image":"/:","blobContainer":"images","blobBaseName":"repo--tag.tar.gz"} +EOF +} + +# Parse args +ACR_NAME="" +STORAGE_ACCOUNT="" +QUEUE_NAME="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --acr-name) + ACR_NAME="${2:-}"; shift 2 ;; + --storage-account) + STORAGE_ACCOUNT="${2:-}"; shift 2 ;; + --queue-name) + QUEUE_NAME="${2:-}"; shift 2 ;; + --blob-container) + BLOB_CONTAINER="${2:-}"; shift 2 ;; + --output-file) + OUTPUT_FILE="${2:-}"; shift 2 ;; + --enqueue) + ENQUEUE=1; shift ;; + --repo-prefix) + REPO_PREFIX="${2:-}"; shift 2 ;; + --exclude-tag) + EXCLUDE_TAGS+=("${2:-}"); shift 2 ;; + --include-untagged) + case "${2:-}" in + true|TRUE|1) INCLUDE_UNTAGGED=1 ;; + false|FALSE|0) INCLUDE_UNTAGGED=0 ;; + *) die "invalid value for --include-untagged: ${2:-}" ;; + esac + shift 2 ;; + -h|--help) + usage; exit 0 ;; + *) + die "unknown argument: $1" ;; + esac +done + +[[ -n "${ACR_NAME}" ]] || die "--acr-name is required" +[[ -n "${STORAGE_ACCOUNT}" ]] || die "--storage-account is required" +[[ -n "${QUEUE_NAME}" ]] || die "--queue-name is required" + +require_cmd az +require_cmd jq + +if [[ -n "${OUTPUT_FILE}" ]]; then + : > "${OUTPUT_FILE}" + vlog "Initialized output file ${OUTPUT_FILE}" +fi + +LOGIN_SERVER="${ACR_NAME}.azurecr.io" + +acr_args=(--name "${ACR_NAME}") +# Azure CLI supports --username/--password for az acr repository commands. :contentReference[oaicite:1]{index=1} +if [[ -n "${ACR_USERNAME:-}" && -n "${ACR_PASSWORD:-}" ]]; then + acr_args+=(--username "${ACR_USERNAME}" --password "${ACR_PASSWORD}") + log "Using explicit ACR credentials for repository enumeration" +else + log "Using current az login context for repository enumeration" +fi + +sanitize_blob_basename() { + local repo="$1" + local tag="$2" + + # Keep slash out of blob basename and use -- instead of : + local safe_repo safe_tag + safe_repo="${repo//\//__}" + safe_tag="${tag//:/--}" + + printf '%s--%s.tar.gz' "${safe_repo}" "${safe_tag}" +} + +should_exclude_tag() { + local tag="$1" + local excluded + for excluded in "${EXCLUDE_TAGS[@]:-}"; do + if [[ "${tag}" == "${excluded}" ]]; then + return 0 + fi + done + return 1 +} + +enqueue_message() { + local json="$1" + + # az storage message put adds a message to the queue. The command group supports + # auth parameters including --auth-mode. :contentReference[oaicite:2]{index=2} + az storage message put \ + --auth-mode login \ + --account-name "${STORAGE_ACCOUNT}" \ + --queue-name "${QUEUE_NAME}" \ + --content "${json}" \ + --time-to-live -1 \ + --output none +} + +log "Listing repositories from ${ACR_NAME}" +repos_json="$(az acr repository list "${acr_args[@]}" --output json)" +repo_count="$(jq 'length' <<<"${repos_json}")" +log "Found ${repo_count} repositories" + +count_messages=0 +count_repos=0 + +while IFS= read -r repo; do + [[ -n "${repo}" ]] || continue + + if [[ -n "${REPO_PREFIX}" && "${repo}" != "${REPO_PREFIX}"* ]]; then + vlog "Skipping repo ${repo} due to prefix filter" + continue + fi + + count_repos=$((count_repos + 1)) + log "Enumerating tags for repo ${repo}" + + # show-tags is the documented command for tags; --detail is supported if you want richer output. :contentReference[oaicite:3]{index=3} + tags_json="$(az acr repository show-tags "${acr_args[@]}" --repository "${repo}" --output json)" + tag_count="$(jq 'length' <<<"${tags_json}")" + vlog "Repo ${repo} returned ${tag_count} tags" + + if [[ "${tag_count}" -eq 0 && "${INCLUDE_UNTAGGED}" -eq 1 ]]; then + vlog "Repo ${repo} has no tags; skipping because worker expects explicit tag" + fi + + while IFS= read -r tag; do + [[ -n "${tag}" ]] || continue + + if should_exclude_tag "${tag}"; then + vlog "Skipping ${repo}:${tag} due to exclude filter" + continue + fi + + image_ref="${LOGIN_SERVER}/${repo}:${tag}" + blob_base_name="$(sanitize_blob_basename "${repo}" "${tag}")" + + message_json="$( + jq -cn \ + --arg image "${image_ref}" \ + --arg blobContainer "${BLOB_CONTAINER}" \ + --arg blobBaseName "${blob_base_name}" \ + '{ + image: $image, + blobContainer: $blobContainer, + blobBaseName: $blobBaseName + }' + )" + + if [[ -n "${OUTPUT_FILE}" ]]; then + printf '%s\n' "${message_json}" >> "${OUTPUT_FILE}" + fi + + if [[ "${ENQUEUE}" -eq 1 ]]; then + log "Enqueueing ${image_ref} -> ${BLOB_CONTAINER}/${blob_base_name}" + enqueue_message "${message_json}" + else + vlog "Prepared ${image_ref} -> ${BLOB_CONTAINER}/${blob_base_name}" + fi + + count_messages=$((count_messages + 1)) + done < <(jq -r '.[]' <<<"${tags_json}") + +done < <(jq -r '.[]' <<<"${repos_json}") + +log "Completed repository scan" +log "Processed repositories: ${count_repos}" +log "Prepared messages: ${count_messages}" + +if [[ -n "${OUTPUT_FILE}" ]]; then + log "Wrote JSONL messages to ${OUTPUT_FILE}" +fi