Path: blob/master/hack/update-template-almalinux-kitten.sh
1637 views
#!/usr/bin/env bash12# SPDX-FileCopyrightText: Copyright The Lima Authors3# SPDX-License-Identifier: Apache-2.045set -eu -o pipefail67# Functions in this script assume error handling with 'set -e'.8# To ensure 'set -e' works correctly:9# - Use 'set +e' before assignments and '$(set -e; <function>)' to capture output without exiting on errors.10# - Avoid calling functions directly in conditions to prevent disabling 'set -e'.11# - Use 'shopt -s inherit_errexit' (Bash 4.4+) to avoid repeated 'set -e' in all '$(...)'.12shopt -s inherit_errexit || error_exit "inherit_errexit not supported. Please use bash 4.4 or later."1314function almalinux_kitten_print_help() {15cat <<HELP16$(basename "${BASH_SOURCE[0]}"): Update the AlmaLinux Kitten image location in the specified templates1718Usage:19$(basename "${BASH_SOURCE[0]}") [--version-major <major version>] <template.yaml>...2021Description:22This script updates the AlmaLinux Kitten image location in the specified templates.23If the image location in the template contains a minor version and release date in the URL,24the script replaces it with the latest available minor version and date.2526Image location basename format:2728AlmaLinux-Kitten-GenericCloud-<major version>-[latest|<date>.<release>].<arch>.qcow22930Published AlmaLinux Kitten image information is fetched from the following URLs:3132https://kitten.repo.almalinux.org/<major version>-kitten/cloud/<arch>/images/3334To parsing html, this script requires 'htmlq' or 'pup' command.35The downloaded files will be cached in the Lima cache directory.3637Examples:38Update the AlmaLinux Kitten image location in templates/**.yaml:39$ $(basename "${BASH_SOURCE[0]}") templates/**.yaml4041Update the AlmaLinux Kitten image location in ~/.lima/almalinux-kitten/lima.yaml:42$ $(basename "${BASH_SOURCE[0]}") ~/.lima/almalinux-kitten/lima.yaml43$ limactl factory-reset almalinux-kitten4445Update the AlmaLinux Kitten image location to major version 10 in ~/.lima/almalinux-kitten/lima.yaml:46$ $(basename "${BASH_SOURCE[0]}") --version-major 10 ~/.lima/almalinux-kitten/lima.yaml47$ limactl factory-reset almalinux-kitten4849Flags:50--version-major <version> Use the specified version. The version must be 10 or later.51-h, --help Print this help message52HELP53}5455# print the URL spec for the given location56function almalinux_kitten_url_spec_from_location() {57local location=$1 jq_filter url_spec58jq_filter='capture(59"^https://kitten\\.repo\\.almalinux\\.org/(?<path_version>\\d+)-kitten/cloud/(?<path_arch>[^/]+)/images/" +60"AlmaLinux-Kitten-(?<target_vendor>.*)-(?<major_version>\\d+)-" +61"(latest|(?<date>\\d{8}(\\\\d+)?))\\.(?<release>\\d+)\\.(?<arch>[^.]+).(?<file_extension>.*)$"62;"x")63'64url_spec=$(jq -e -r "${jq_filter}" <<<"\"${location}\"")6566jq -e '.path_arch == .arch' <<<"${url_spec}" >/dev/null ||67error_exit "Validation failed: .path_arch != .arch: ${location}"68echo "${url_spec}"69}7071readonly almalinux_kitten_jq_filter_directory='"https://kitten.repo.almalinux.org/\(.path_version)-kitten/cloud/\(.path_arch)/images/"'72readonly almalinux_kitten_jq_filter_filename='"AlmaLinux-Kitten-\(.target_vendor)-\(.major_version)-\(if .date then .date + ".0" else "latest" end).\(.arch).\(.file_extension)"'7374# print the location for the given URL spec75function almalinux_kitten_location_from_url_spec() {76local -r url_spec=$177jq -e -r "${almalinux_kitten_jq_filter_directory} + ${almalinux_kitten_jq_filter_filename}" <<<"${url_spec}" ||78error_exit "Failed to get the location for ${url_spec}"79}8081function almalinux_kitten_image_directory_from_url_spec() {82local -r url_spec=$183jq -e -r "${almalinux_kitten_jq_filter_directory}" <<<"${url_spec}" ||84error_exit "Failed to get the image directory for ${url_spec}"85}8687function almalinux_kitten_image_filename_from_url_spec() {88local -r url_spec=$189jq -e -r "${almalinux_kitten_jq_filter_filename}" <<<"${url_spec}" ||90error_exit "Failed to get the image filename for ${url_spec}"91}9293#94function almalinux_kitten_latest_image_entry_for_url_spec() {95local url_spec=$1 arch major_version_url_spec major_version_image_directory downloaded_page links_in_page latest_minor_version_info96arch=$(jq -r '.arch' <<<"${url_spec}")97# to detect minor version updates, we need to get the major version URL98major_version_url_spec=$(jq -e -r '.path_version = .major_version' <<<"${url_spec}")99major_version_image_directory=$(almalinux_kitten_image_directory_from_url_spec "${major_version_url_spec}")100downloaded_page=$(download_to_cache "${major_version_image_directory}")101if command -v htmlq >/dev/null; then102links_in_page=$(htmlq 'pre a' --attribute href <"${downloaded_page}")103elif command -v pup >/dev/null; then104links_in_page=$(pup 'pre a attr{href}' <"${downloaded_page}")105else106error_exit "Please install 'htmlq' or 'pup' to list images from ${major_version_image_directory}"107fi108latest_minor_version_info=$(jq -e -Rrs --argjson spec "${url_spec}" '109[110split("\n").[] |111capture(112"^AlmaLinux-Kitten-\($spec.target_vendor)-" +113"(?<major_minor_version>\($spec.major_version))-" +114"(?<date>\\d{8})\\.(?<release>\\d)+\\.\($spec.arch)\\.\($spec.file_extension)$"115;"x"116) |117.version_number_array = ([.major_minor_version | scan("\\d+") | tonumber])118] | sort_by(.version_number_array, .date_and_ci_job_id) | last119' <<<"${links_in_page}")120[[ -n ${latest_minor_version_info} ]] || return121local newer_url_spec location directory checksum_location downloaded_sha256sum filename digest122# prefer the major_minor_version in the path123newer_url_spec=$(jq -e -r ". + ${latest_minor_version_info} | .path_version = .major_minor_version" <<<"${url_spec}")124location=$(almalinux_kitten_location_from_url_spec "${newer_url_spec}")125directory=$(almalinux_kitten_image_directory_from_url_spec "${newer_url_spec}")126checksum_location="${directory}CHECKSUM"127downloaded_sha256sum=$(download_to_cache "${checksum_location}")128filename=$(almalinux_kitten_image_filename_from_url_spec "${newer_url_spec}")129digest=$(awk "/${filename}/{print \"sha256:\"\$1}" "${downloaded_sha256sum}")130[[ -n ${digest} ]] || error_exit "Failed to get the SHA256 digest for ${filename}"131json_vars location arch digest132}133134function almalinux_kitten_cache_key_for_image_kernel() {135local location=$1 url_spec136url_spec=$(almalinux_kitten_url_spec_from_location "${location}")137jq -r '["almalinux-kitten", .major_minor_version // .major_version, .target_vendor,138if .date then "timestamped" else "latest" end,139.arch, .file_extension] | join(":")' <<<"${url_spec}"140}141142function almalinux_kitten_image_entry_for_image_kernel() {143local location=$1 kernel_is_not_supported=$2 overriding=${3:-"{}"} url_spec image_entry=''144[[ ${kernel_is_not_supported} == "null" ]] || echo "Updating kernel information is not supported on AlmaLinux Kitten" >&2145url_spec=$(almalinux_kitten_url_spec_from_location "${location}" | jq -r ". + ${overriding}")146if jq -e '.date' <<<"${url_spec}" >/dev/null; then147image_entry=$(almalinux_kitten_latest_image_entry_for_url_spec "${url_spec}")148else149image_entry=$(150# shellcheck disable=SC2030151location=$(almalinux_kitten_location_from_url_spec "${url_spec}")152location=$(validate_url_without_redirect "${location}")153arch=$(jq -r '.path_arch' <<<"${url_spec}")154json_vars location arch155)156fi157# shellcheck disable=SC2031158if [[ -z ${image_entry} ]]; then159error_exit "Failed to get the ${url_spec} image location for ${location}"160elif jq -e ".location == \"${location}\"" <<<"${image_entry}" >/dev/null; then161echo "Image location is up-to-date: ${location}" >&2162else163echo "${image_entry}"164fi165}166167# check if the script is executed or sourced168# shellcheck disable=SC1091169if [[ ${BASH_SOURCE[0]} == "${0}" ]]; then170scriptdir=$(dirname "${BASH_SOURCE[0]}")171# shellcheck source=./cache-common-inc.sh172. "${scriptdir}/cache-common-inc.sh"173174if ! command -v htmlq >/dev/null && ! command -v pup >/dev/null; then175error_exit "Please install 'htmlq' or 'pup' to list images from https://kitten.repo.almalinux.org/<version>-kitten/cloud/<arch>/images/"176fi177# shellcheck source=/dev/null # avoid shellcheck hangs on source looping178. "${scriptdir}/update-template.sh"179else180# this script is sourced181if ! command -v htmlq >/dev/null && ! command -v pup >/dev/null; then182echo "Please install 'htmlq' or 'pup' to list images from https://kitten.repo.almalinux.org/<version>-kitten/cloud/<arch>/images/" >&2183elif [[ -v SUPPORTED_DISTRIBUTIONS ]]; then184SUPPORTED_DISTRIBUTIONS+=("almalinux-kitten")185else186declare -a SUPPORTED_DISTRIBUTIONS=("almalinux-kitten")187fi188return 0189fi190191declare -a templates=()192declare overriding="{}"193while [[ $# -gt 0 ]]; do194case "$1" in195-h | --help)196almalinux_kitten_print_help197exit 0198;;199-d | --debug) set -x ;;200--version-major)201if [[ -n $2 && $2 != -* ]]; then202overriding=$(203major_version="${2%%.*}"204[[ ${major_version} -ge 10 ]] || error_exit "AlmaLinux Kitten major version must be 8 or later"205# shellcheck disable=2034206path_version="${major_version}"207json_vars path_version major_version <<<"${overriding}"208)209shift210else211error_exit "--version-major requires a value"212fi213;;214--version-major=*)215overriding=$(216major_version="${1#*=}"217major_version="${major_version%%.*}"218[[ ${major_version} -ge 10 ]] || error_exit "AlmaLinux Kitten major version must be 8 or later"219# shellcheck disable=2034220path_version="${major_version}"221json_vars path_version major_version <<<"${overriding}"222)223;;224*.yaml) templates+=("$1") ;;225*)226error_exit "Unknown argument: $1"227;;228esac229shift230[[ -z ${overriding} ]] && overriding="{}"231done232233if [[ ${#templates[@]} -eq 0 ]]; then234almalinux_kitten_print_help235exit 0236fi237238declare -A image_entry_cache=()239240for template in "${templates[@]}"; do241echo "Processing ${template}"242# 1. extract location by parsing template using arch243yq_filter="244.images[] | [.location, .kernel.location, .kernel.cmdline] | @tsv245"246parsed=$(yq eval "${yq_filter}" "${template}")247248# 3. get the image location249arr=()250while IFS= read -r line; do arr+=("${line}"); done <<<"${parsed}"251locations=("${arr[@]}")252for ((index = 0; index < ${#locations[@]}; index++)); do253[[ ${locations[index]} != "null" ]] || continue254set -e255IFS=$'\t' read -r location kernel_location kernel_cmdline <<<"${locations[index]}"256set +e # Disable 'set -e' to avoid exiting on error for the next assignment.257cache_key=$(258set -e # Enable 'set -e' for the next command.259almalinux_kitten_cache_key_for_image_kernel "${location}" "${kernel_location}"260) # Check exit status separately to prevent disabling 'set -e' by using the function call in the condition.261# shellcheck disable=2181262[[ $? -eq 0 ]] || continue263image_entry=$(264set -e # Enable 'set -e' for the next command.265if [[ -v image_entry_cache[${cache_key}] ]]; then266echo "${image_entry_cache[${cache_key}]}"267else268almalinux_kitten_image_entry_for_image_kernel "${location}" "${kernel_location}" "${overriding}"269fi270) # Check exit status separately to prevent disabling 'set -e' by using the function call in the condition.271# shellcheck disable=2181272[[ $? -eq 0 ]] || continue273set -e274image_entry_cache[${cache_key}]="${image_entry}"275if [[ -n ${image_entry} ]]; then276[[ ${kernel_cmdline} != "null" ]] &&277jq -e 'has("kernel")' <<<"${image_entry}" >/dev/null &&278image_entry=$(jq ".kernel.cmdline = \"${kernel_cmdline}\"" <<<"${image_entry}")279echo "${image_entry}" | jq280limactl edit --log-level error --set "281.images[${index}] = ${image_entry}|282(.images[${index}] | ..) style = \"double\"283" "${template}"284fi285done286done287288289