#!/bin/bash : "${CACHE_DIR:=$PWD/AppData/Local/K3s-Cache}" DOWNLOAD_URL="https://github.com/k3s-io/k3s/releases/download" # This function determines the latest k3s build for a given k8s version. # Starting with the latest cached version, it checks if any newer versions # are available from Github. # # NOTE: This function does *NOT* verify that build 1 exists, i.e. that # the provided k8s version is valid. This will be detected by the actual # download attempt. function latest_build { local k8s_version="$1" # check if the k8s version already includes the k3s build suffix local regex='\+k3s[0-9]+$' if [[ ${k8s_version} =~ ${regex} ]]; then echo "${k8s_version}" return fi # locate latest k3s build of k8s_version in the cache local k3s_build k3s_build=$(ls -1d "${CACHE_DIR}/${k8s_version}"+k3s* 2>/dev/null \ | sed 's/.*+k3s//' | sort -h -r | head -1) # if no cached version exists, assume at least build 1 exist on Github. if [ -z "${k3s_build}" ]; then k3s_build=1 fi # find latest published build (there may be tags that don't have builds) while true; do local version="${k8s_version}+k3s$((k3s_build+1))" local url="${DOWNLOAD_URL}/${version}/k3s" # TODO: what is a reasonable timeout to assume no internet connectivity? if ! wget --quiet --spider --tries 1 --timeout 5 -O /dev/null "${url}"; then echo "${k8s_version}+k3s${k3s_build}" return fi k3s_build=$((k3s_build+1)) done } # Verify that the current directory has a complete set of downloaded binaries. function verify_binaries { # Verify sha256sum only once after download to check for # truncated files; it takes several seconds to run. if [ -f .verified ]; then # Just make sure the files still exist for asset in k3s k3s-airgap-images-amd64.tar; do if [ ! -f ${asset} ]; then return 1 fi done return 0 fi if [ ! -f sha256sum-amd64.txt ]; then return 1 fi # Don't look for k3s-images.txt; we don't download it. # `sha256sum --ignore-missing --check` doesn't seem to work. if ! cat sha256sum-amd64.txt | grep -v txt$ | sha256sum --quiet --check; then return 1 fi touch .verified } # Download binaries for specified k8s version and return the fully qualified # path to the cache directory. Non-zero exit means the binaries don't exist # or couldn't be downloaded. function get_binaries { local version version="$(latest_build "$1")" local dir="${CACHE_DIR}/${version}" mkdir -p "${dir}" pushd "${dir}" >/dev/null if ! verify_binaries; then for asset in k3s k3s-airgap-images-amd64.tar sha256sum-amd64.txt; do if ! wget --quiet --output-document "${asset}" \ "${DOWNLOAD_URL}/${version}/${asset}"; then rm "${asset}" fi done if ! verify_binaries; then >&2 echo "Version ${version} is not in cache and couldn't be downloaded" popd >/dev/null rmdir "${dir}" return 1 fi fi popd >/dev/null echo "${dir}/${version}" } for version in "$@"; do get_binaries "${version}" done