#!/usr/bin/env bash set -Eeuo pipefail R2_BASE_URL="https://zvm2-dev.zimaos.com" VERSION=latest RAW_NAME="zimaos_zvm2.raw" SERVICE="zimaos-virt-management.service" TARGET_DIR=/DATA/.extensions LOCK_FILE=/run/lock/zvm2-install.lock work_dir="" transaction_started=0 enable_attempted=0 had_raw=0 was_active=0 was_enabled=0 rollback_failed=0 usage() { cat <<'EOF' Usage: install-zvm2.sh [--version VERSION] [--help] Install or upgrade the ZVM2 system extension in /DATA/.extensions. Downloads only from https://zvm2-dev.zimaos.com and manages zimaos-virt-management.service. No minimum ZimaOS version is required. By default (or with --version latest), reads latest.json once to select the release. --version VERSION downloads that exact version without latest.json. RAW location: //zimaos_zvm2.raw Resolving latest requires jq or python3; no checksum file is downloaded. Examples: sudo bash install-zvm2.sh sudo bash install-zvm2.sh --version v1.8.1-dev6 Requires root and ZimaOS. Checks the download is non-empty before stopping the service, then refreshes systemd-sysext and enables/starts the service. Does not use zpkg. On failure, attempts to restore the previous RAW and service state. Existing VM data is not removed; application data migrations cannot be undone. EOF } fail() { printf '[ERROR] %s\n' "$*" >&2; exit 1; } valid_version() { [[ $1 =~ ^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$ && $1 != latest ]] } # Parse remote metadata as data; never execute it or accept arbitrary RAW paths. parse_release() { local descriptor=$1 if [[ $json_parser == jq ]]; then jq --exit-status --raw-output --arg name "$RAW_NAME" ' select(.module_id == "zimaos_zvm2") | select(.version | type == "string") | select(.raw.key == (.version + "/" + $name)) | .version ' "$descriptor" else python3 - "$descriptor" "$RAW_NAME" <<'PY' import json import sys try: with open(sys.argv[1], encoding='utf-8') as descriptor: release = json.load(descriptor) if not isinstance(release, dict) or release.get('module_id') != 'zimaos_zvm2': raise ValueError('Unexpected module') version, raw = release.get('version'), release.get('raw') if not isinstance(version, str) or not isinstance(raw, dict) or raw.get('key') != version + '/' + sys.argv[2]: raise ValueError('Invalid version or RAW path') print(version) except (OSError, ValueError, TypeError) as error: print('Invalid ZVM2 release descriptor: ' + str(error), file=sys.stderr) sys.exit(1) PY fi } # Restore via rename, not by overwriting an image that may still be mounted. restore_file() { local destination=$1 backup=$2 existed=$3 if ((existed)); then cp -a -- "$backup" "$work_dir/restore" && mv -f -- "$work_dir/restore" "$destination" else rm -f -- "$destination" fi } rollback() { printf 'Installation failed; restoring the previous extension and service state.\n' >&2 if systemctl cat "$SERVICE" >/dev/null 2>&1 || systemctl is-active --quiet "$SERVICE"; then systemctl stop "$SERVICE" || rollback_failed=1 fi if ((enable_attempted)); then if ((was_enabled)); then systemctl enable "$SERVICE" || rollback_failed=1 else systemctl disable "$SERVICE" || rollback_failed=1 fi fi restore_file "$raw_path" "$work_dir/previous.raw" "$had_raw" || rollback_failed=1 systemd-sysext refresh || rollback_failed=1 systemctl daemon-reload || rollback_failed=1 if ((was_active && !rollback_failed)); then systemctl start "$SERVICE" || rollback_failed=1 systemctl is-active --quiet "$SERVICE" || rollback_failed=1 fi } cleanup() { local status=$? trap - EXIT HUP INT TERM set +e if ((transaction_started)); then # A truncated streamed installer must not leave a partial installation. if ((status == 0)); then status=1; fi rollback fi if ((rollback_failed)); then printf 'Rollback did not fully succeed. Recovery files: %s\n' "$work_dir" >&2 elif [[ -n $work_dir ]]; then rm -rf -- "$work_dir" fi exit "$status" } download_package() { local raw_url=$1 curl "${curl_options[@]}" --progress-bar \ --output "$work_dir/package.raw" "$raw_url" || return 1 [[ -s $work_dir/package.raw ]] } main() { while (($#)); do case $1 in --version) if (($# < 2)); then usage >&2; return 2; fi VERSION=$2 shift 2 ;; -h|--help) usage; return 0 ;; *) usage >&2; return 2 ;; esac done [[ $VERSION == latest ]] || valid_version "$VERSION" || fail 'Invalid release version.' [[ $RAW_NAME =~ ^[A-Za-z0-9][A-Za-z0-9._-]*\.raw$ ]] \ || fail 'Set RAW_NAME to the confirmed RAW filename (no directory components).' [[ $SERVICE =~ ^[A-Za-z0-9][A-Za-z0-9_.@-]*\.service$ ]] \ || fail 'Set SERVICE to the confirmed systemd service name.' [[ $R2_BASE_URL == https://?* ]] || fail 'Configure an HTTPS R2 base URL.' [[ $(id -u) == 0 ]] || fail 'Run this installer as root.' for tool in curl systemctl systemd-sysext systemd-analyze flock \ mktemp install cp mv rm chmod dirname; do command -v "$tool" >/dev/null || fail "Required command not found: $tool" done local json_parser="" if [[ $VERSION == latest ]]; then if command -v jq >/dev/null; then json_parser=jq elif command -v python3 >/dev/null; then json_parser=python3 else fail 'Resolving latest requires jq or python3; alternatively, use --version VERSION.' fi fi systemd-analyze condition 'ConditionOSRelease=ID=zimaos' >/dev/null 2>&1 \ || fail 'This installer requires ZimaOS.' [[ ! -L $TARGET_DIR ]] || fail "Extension directory must not be a symlink: $TARGET_DIR" raw_path="$TARGET_DIR/$RAW_NAME" [[ ! -L $raw_path && ( ! -e $raw_path || -f $raw_path ) ]] \ || fail "Expected a regular file: $raw_path" umask 077 install -d -m 0755 "$(dirname "$LOCK_FILE")" exec 9>"$LOCK_FILE" flock -n 9 || fail 'Another ZVM2 installation is running.' trap cleanup EXIT trap 'exit 130' INT trap 'exit 143' HUP TERM install -d -m 0755 "$TARGET_DIR" work_dir=$(mktemp -d "$TARGET_DIR/.zvm2-install.XXXXXX") local -a curl_options=(--fail --show-error --location --retry 2 --retry-delay 1 --connect-timeout 10 --max-time 300 --proto '=https' --proto-redir '=https') if [[ $VERSION == latest ]]; then printf 'Checking the latest ZVM2 release ...\n' curl "${curl_options[@]}" --silent --max-time 30 --max-filesize 65536 \ --output "$work_dir/latest.json" "${R2_BASE_URL%/}/latest.json" \ || fail 'Unable to download the ZVM2 release descriptor.' VERSION=$(parse_release "$work_dir/latest.json") \ || fail 'Unable to read a valid ZVM2 release descriptor.' fi valid_version "$VERSION" || fail 'Invalid release version in latest.json.' printf 'Downloading ZVM2 %s from R2 ...\n' "$VERSION" download_package "${R2_BASE_URL%/}/$VERSION/$RAW_NAME" \ || fail 'Unable to download a non-empty ZVM2 RAW. The existing installation was not changed.' chmod 0644 "$work_dir/package.raw" systemctl is-active --quiet "$SERVICE" && was_active=1 || true systemctl is-enabled --quiet "$SERVICE" && was_enabled=1 || true if [[ -f $raw_path ]]; then cp -a -- "$raw_path" "$work_dir/previous.raw"; had_raw=1; fi transaction_started=1 if systemctl cat "$SERVICE" >/dev/null 2>&1 || ((was_active)); then systemctl stop "$SERVICE" fi mv -f -- "$work_dir/package.raw" "$raw_path" systemd-sysext refresh systemctl daemon-reload enable_attempted=1 systemctl enable "$SERVICE" systemctl start "$SERVICE" systemctl is-active --quiet "$SERVICE" systemctl is-enabled --quiet "$SERVICE" transaction_started=0 printf 'ZVM2 %s is installed at %s. %s is running and enabled at boot.\n' "$VERSION" "$raw_path" "$SERVICE" } script_source="${BASH_SOURCE[0]-}" if [[ -z $script_source || $script_source == "$0" ]]; then main "$@" fi