From e687f4acd80800708d47b94b075eb2522390b63e Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Tue, 24 Nov 2026 18:04:17 -0600 Subject: [PATCH 1/9] Add offline Linux NVMe preparation action Embed the shared Linux preparation script with guest-kernel/device adapters and the tested RHEL 7 standalone EFI timeout correction. Add self-contained action regressions and optional shared-source fixtures. Document the unchanged Oracle framework limitation and SSH acceptance gap; keep ADE and session-specific deployment tooling outside this change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 60 +++ src/action_implementation/nvme-impl.sh | 711 +++++++++++++++++++++++++ src/constants.rs | 1 + src/helper.rs | 6 + tests/nvme/README.md | 114 ++++ tests/nvme/run_tests.py | 431 +++++++++++++++ tests/nvme/test_efi_timeout.py | 152 ++++++ tests/nvme/test_offline.py | 116 ++++ tests/nvme/test_runner.py | 91 ++++ 9 files changed, 1682 insertions(+) create mode 100644 src/action_implementation/nvme-impl.sh create mode 100644 tests/nvme/README.md create mode 100644 tests/nvme/run_tests.py create mode 100644 tests/nvme/test_efi_timeout.py create mode 100644 tests/nvme/test_offline.py create mode 100644 tests/nvme/test_runner.py diff --git a/README.md b/README.md index a5799c1..03abc8c 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,66 @@ This action corrects two issues that can happen when a new kernel gets installed This action enables both the serialconsole and the GRUB serial. Incorrect vaules get overwritten by a set of defaults The correct setup allows you to see the `GRUB Menu` as well get access to the system via the `Azure Serial Console`. +#### nvme +This action prepares the attached Linux guest for NVMe using the Linux preparation +logic from the Azure CLI `nvme-conversion` extension. Run it with `alar nvme`. +It preserves the original Linux script's checks and conditional fixes: built-in +and initramfs driver detection, NVMe/Hyper-V PCI driver preparation, +`nvme_core.io_timeout=240`, optional BLS updates, fallback Azure NVMe udev rules, +and SCSI-to-UUID fstab conversion. Existing ready configurations are skipped. +The original distro-specific branches, legacy release-file detection, image +exclusions and diagnostic/error reporting are retained; no additional health +checks or Azure VM size/controller changes are introduced. + +The script retains branches for Ubuntu, Debian, RHEL/CentOS/Rocky/AlmaLinux, +SLES, Oracle Linux, Azure Linux and Mariner. It uses installed guest kernels +rather than the running rescue kernel. Live udev reload is deferred to the guest's +next boot. Script coverage does not guarantee that every image or VM size supports +NVMe. + +On RHEL/CentOS 7, a standalone EFI configuration selected by `/etc/grub2-efi.cfg` +is checked and regenerated at that actual target. Every kernel entry must have +exactly one `nvme_core.io_timeout=240` argument. Broken links, redirect stubs and +failed or ineffective regeneration are reported rather than accepted from an +unrelated GRUB configuration. Other release and BIOS paths retain the shared +script's behavior. + +Fstab device identities are resolved from mounted guest filesystems, including +other partitions on those same disks. Unmounted data disks and swap can also be +resolved with an explicit, guest-visible device map. Set `ALAR_NVME_DEVICE_MAP` +to a file containing one original-device rescue-device pair per line, for example: + +```text +/dev/sda /dev/sdd +/dev/disk/azure/scsi1/lun0 /dev/nvme1n1 +``` + +Mappings can name whole disks or individual partitions. Use only independently +identified attached guest devices, not rescue OS devices. For example, with the +map saved on the rescue VM as `/tmp/nvme-device-map`, run +`ALAR_NVME_DEVICE_MAP=/tmp/nvme-device-map alar nvme`. +Unresolved devices are left unchanged with a warning; the action does not guess +that an old guest device name still identifies the same disk on the rescue VM. +The original fstab backup remains `/etc/fstab.bak`. + +ALAR defaults to applying fixes. Within an already prepared guest chroot, the +script also supports `bash /tmp/action_implementation/nvme-impl.sh -check` for +the original check-only behavior and `bash /tmp/action_implementation/nvme-impl.sh -dryrun` +for the original staged changes, diffs and summary under `/tmp/nvme-conversion-dryrun/`. +These script modes do not add arguments to ALAR's CLI. + +**Known framework limitation:** some Oracle Linux disk layouts are classified as +ADE-encrypted before ALAR reaches the action. Oracle Linux 8.10, 9.8 and 9.7 passed +full action/conversion testing with a separate temporary framework patch, but +that patch was reverted and is not included here. Those results do not mean the +unchanged framework can process those layouts. Genuine ADE credential recovery +and reliable post-conversion SSH connectivity are not certified by these tests. + +The original diagnostic and exit behavior is preserved: review the action output, +not just ALAR's exit status, when evaluating preparation results. +The [NVMe test guide](tests/nvme/README.md) documents the self-contained regression +suite, optional shared-source comparisons, completed live coverage and limits. + #### grubfix This action is reinstalling `GRUB` and regenerates the `grub.cfg` file diff --git a/src/action_implementation/nvme-impl.sh b/src/action_implementation/nvme-impl.sh new file mode 100644 index 0000000..d22443f --- /dev/null +++ b/src/action_implementation/nvme-impl.sh @@ -0,0 +1,711 @@ +#!/bin/bash + +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the terms found in the LICENSE file in the root of this source tree. + +# Linux script from the nvme-conversion CLI extension, with offline guest +# kernel/device resolution and fix mode as the ALAR default. + +guest_kernel_version() { + printf '%s\n' "$guest_kernel" +} + +scsi_device_parts() { + if [[ "$1" =~ ^(/dev/sd[a-z]+)([0-9]*)$ ]]; then + printf '%s %s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + elif [[ "$1" =~ ^(/dev/disk/azure/scsi[0-9]+/lun[0-9]+)(-part([0-9]+))?$ ]]; then + printf '%s %s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[3]}" + else + return 1 + fi +} + +guest_partition_device() { + local disk partition="$2" + disk=$(readlink -f "$1") || return 1 + if [ -z "$partition" ]; then + printf '%s\n' "$disk" + elif [[ "$disk" =~ [0-9]$ ]]; then + printf '%sp%s\n' "$disk" "$partition" + else + printf '%s%s\n' "$disk" "$partition" + fi +} + +resolve_guest_device() { + local device="$1" disk partition original target extra parts + parts=$(scsi_device_parts "$device") || return 1 + read -r disk partition <<< "$parts" + + # Explicit identities also cover unmounted data disks and swap. The map is + # guest-visible, with one original-device rescue-device pair per line. + if [ -n "${ALAR_NVME_DEVICE_MAP:-}" ]; then + if [ ! -r "$ALAR_NVME_DEVICE_MAP" ]; then + echo "[ERROR] Cannot read device map: $ALAR_NVME_DEVICE_MAP" >&2 + return 1 + fi + while read -r original target extra || [ -n "$original" ]; do + [[ -z "$original" || "$original" == \#* ]] && continue + if [[ "$original" != /dev/* || "$target" != /dev/* || -n "$extra" ]]; then + echo "[ERROR] Invalid device map entry: $original $target $extra" >&2 + return 1 + fi + if [ "$original" = "$device" ]; then + printf '%s\n' "$target" + return + fi + if [[ -n "$disk" && "$original" = "$disk" ]]; then + guest_partition_device "$target" "$partition" + return + fi + done < "$ALAR_NVME_DEVICE_MAP" + fi + + local spec mountpoint rest mounted_device parent source_disk source_partition + while read -r spec mountpoint rest || [ -n "$spec" ]; do + [[ -z "$spec" || "$spec" == \#* || "$mountpoint" = none ]] && continue + if ! parts=$(scsi_device_parts "$spec"); then + continue + fi + read -r source_disk source_partition <<< "$parts" + [[ -n "$source_disk" && "$source_disk" = "$disk" ]] || continue + if ! mounted_device=$(findmnt -rn -o SOURCE --mountpoint "$(printf '%b' "$mountpoint")"); then + continue + fi + mounted_device="${mounted_device%%\[*}" + if [ "$spec" = "$device" ]; then + printf '%s\n' "$mounted_device" + return + fi + parent=$(lsblk -dnro PKNAME "$mounted_device") || return 1 + if [[ -n "$parent" && "$parent" != *$'\n'* ]]; then + guest_partition_device "/dev/$parent" "$partition" + return + fi + done < /etc/fstab + return 1 +} + +guest_blkid() { + local device + if ! device=$(resolve_guest_device "$1"); then + echo "[WARNING] Cannot map guest device $1 to an attached disk. Supply ALAR_NVME_DEVICE_MAP for unmounted or ambiguous devices." >&2 + return 1 + fi + command blkid -c /dev/null "$device" +} + +# Set default values +fix=true +dry_run=false +distro="" + +# Staging directory for dry-run mode +staging_dir="" + +setup_dryrun() { + staging_dir="/tmp/nvme-conversion-dryrun" + rm -rf "$staging_dir" + mkdir -p "$staging_dir/original" "$staging_dir/modified" "$staging_dir/diffs" + echo "$(hostname)" > "$staging_dir/hostname" + echo "$distro" > "$staging_dir/distro" + guest_kernel_version > "$staging_dir/kernel" + echo "[INFO] Dry-run mode: staging changes in $staging_dir" +} + +# Function to display usage +usage() { + echo "Usage: $0 [-check] [-fix] [-dryrun]" + exit 1 +} + +# Parse command line arguments +while [ $# -gt 0 ]; do + case "$1" in + -check) + fix=false + ;; + -fix) + fix=true + ;; + -dryrun) + dry_run=true + fix=true + ;; + *) + usage + ;; + esac + shift +done + +# Determine the Linux distribution +if [ -f /etc/os-release ]; then + source /etc/os-release + distro="$ID" +elif [ -f /etc/debian_version ]; then + distro="debian" +elif [ -f /etc/SuSE-release ]; then + distro="suse" +elif [ -f /etc/redhat-release ]; then + distro="redhat" +elif [ -f /etc/centos-release ]; then + distro="centos" +elif [ -f /etc/rocky-release ]; then + distro="rocky" +else + echo "[ERROR] Unsupported distribution." + exit 1 +fi +echo "[INFO] Operating system detected: $distro" + +# uname reports the rescue kernel even inside a chroot. Check the original +# driver logic against every installed guest kernel instead. +guest_kernels=() +for modules_dir in /lib/modules/*; do + [ -d "$modules_dir" ] && guest_kernels+=("${modules_dir##*/}") +done +if [ "${#guest_kernels[@]}" -eq 0 ]; then + echo "[ERROR] No installed guest kernels found in /lib/modules." + exit 1 +fi +guest_kernel="${guest_kernels[0]}" + +# Setup dry-run staging if enabled +if $dry_run && $fix; then + setup_dryrun +fi + +# Function to check if azure-vm-utils is installed +check_azure_vm_utils() { + echo "[INFO] Checking for azure-vm-utils..." + + if command -v azure-nvme-id &>/dev/null; then + echo "[INFO] azure-vm-utils is installed (azure-nvme-id found)." + if [ -f /etc/udev/rules.d/80-azure-disk.rules ] || [ -f /lib/udev/rules.d/80-azure-disk.rules ] || [ -f /usr/lib/udev/rules.d/80-azure-disk.rules ]; then + echo "[INFO] 80-azure-disk.rules is present. NVMe disk symlinks and io_timeout will be managed by udev." + else + echo "[WARNING] azure-nvme-id found but 80-azure-disk.rules is missing. Udev symlinks may not work after conversion." + fi + else + echo "[WARNING] azure-vm-utils is not installed." + echo "[WARNING] After conversion, /dev/disk/azure/ symlinks for NVMe disks may not be available." + echo "[WARNING] Install azure-vm-utils from https://github.com/Azure/azure-vm-utils for best NVMe experience." + if $fix; then + _install_fallback_udev_rules + else + echo "[WARNING] Use --fix-os to install a fallback udev rule for basic NVMe symlinks and io_timeout." + fi + fi +} + +# Fallback udev rule for NVMe disks when azure-vm-utils is not available. +# Provides: io_timeout=240s, /dev/disk/azure/root, /dev/disk/azure/data/by-lun/N +# Does NOT provide: by-name, by-serial, by-index (those require azure-nvme-id binary) +# Named 99- so that 80-azure-disk.rules takes precedence if azure-vm-utils is later installed. +_FALLBACK_UDEV_RULE='# Fallback Azure NVMe udev rules (installed by az nvme-conversion) +# Remove this file after installing azure-vm-utils (which provides 80-azure-disk.rules) +ACTION!="add|change", GOTO="azure_nvme_fallback_end" +SUBSYSTEM!="block", GOTO="azure_nvme_fallback_end" +KERNEL!="nvme*", GOTO="azure_nvme_fallback_end" +ENV{ID_MODEL}!="MSFT NVMe Accelerator v1.0", GOTO="azure_nvme_fallback_end" + +# Set io_timeout to 240 seconds for remote NVMe disks +ENV{DEVTYPE}=="disk", ATTRS{nsid}=="?*", ATTR{queue/io_timeout}="240000" + +# OS disk: namespace ID 1 +KERNEL=="nvme*[0-9]n1", ENV{DEVTYPE}=="disk", SYMLINK+="disk/azure/root" +KERNEL=="nvme*[0-9]n1p[0-9]*", ENV{DEVTYPE}=="partition", SYMLINK+="disk/azure/root-part%n" + +# Data disks: namespace ID 2+ maps to LUN = nsid - 2 +KERNEL=="nvme*[0-9]n*[0-9]", ENV{DEVTYPE}=="disk", ATTRS{nsid}!="1", PROGRAM="/bin/sh -ec '\''echo $(($(cat /sys/class/block/%k/nsid) - 2))'\''", SYMLINK+="disk/azure/data/by-lun/%c" +KERNEL=="nvme*[0-9]n*[0-9]p[0-9]*", ENV{DEVTYPE}=="partition", ATTRS{nsid}!="1", PROGRAM="/bin/sh -ec '\''echo $(($(cat /sys/class/block/$(echo %k | sed s/p[0-9]*$//)/nsid) - 2))'\''", SYMLINK+="disk/azure/data/by-lun/%c-part%n" + +LABEL="azure_nvme_fallback_end"' + +_install_fallback_udev_rules() { + local _target="/etc/udev/rules.d/99-azure-nvme-fallback.rules" + + if [ -f "$_target" ]; then + echo "[INFO] Fallback udev rule already installed at $_target" + return + fi + + if $dry_run; then + echo "[DRYRUN] Would install fallback udev rule at $_target" + echo "$_FALLBACK_UDEV_RULE" > "$staging_dir/modified/99-azure-nvme-fallback.rules" + return + fi + + echo "[INFO] Installing fallback NVMe udev rule at $_target" + echo "$_FALLBACK_UDEV_RULE" > "$_target" + echo "[INFO] Offline guest: udev rules will load at the next boot." + echo "[INFO] Fallback udev rule installed. Provides:" + echo "[INFO] - io_timeout=240s for NVMe remote disks" + echo "[INFO] - /dev/disk/azure/root symlink" + echo "[INFO] - /dev/disk/azure/data/by-lun/N symlinks" + echo "[INFO] Note: by-name/by-serial/by-index require azure-vm-utils" +} + +# Function to check if NVMe driver is in initrd/initramfs or built into the kernel +check_nvme_driver() { + echo "[INFO] Checking if NVMe driver is available for boot..." + + # Check if nvme is compiled directly into the kernel (built-in) + if grep -qw nvme "/lib/modules/$(guest_kernel_version)/modules.builtin" 2>/dev/null; then + echo "[INFO] NVMe driver is built into the kernel. No initramfs entry needed." + if $dry_run && $fix; then + echo "[DRYRUN] NVMe driver is built-in (kernel $(guest_kernel_version)). No initramfs or dracut changes needed." + echo "nvme_builtin=true" > "$staging_dir/modified/nvme-driver-status.txt" + echo "kernel=$(guest_kernel_version)" >> "$staging_dir/modified/nvme-driver-status.txt" + grep -w nvme "/lib/modules/$(guest_kernel_version)/modules.builtin" >> "$staging_dir/modified/nvme-driver-status.txt" + fi + return 0 + fi + + echo "[INFO] NVMe is not built-in. Checking initrd/initramfs..." + case "$distro" in + ubuntu|debian) + _initramfs_ok=true + if ! lsinitramfs /boot/initrd.img-* 2>/dev/null | grep -q nvme; then + echo "[WARNING] NVMe driver not found in initrd/initramfs." + _initramfs_ok=false + fi + if ! lsinitramfs /boot/initrd.img-* 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then + echo "[WARNING] pci-hyperv/hv_pci driver not found in initrd/initramfs (required for Azure NVMe)." + _initramfs_ok=false + fi + if $_initramfs_ok; then + echo "[INFO] NVMe driver found in initrd/initramfs." + if $dry_run && $fix; then + echo "[DRYRUN] NVMe and pci-hyperv drivers already in initramfs. No changes needed." + echo "nvme_in_initramfs=true" > "$staging_dir/modified/nvme-driver-status.txt" + echo "kernel=$(guest_kernel_version)" >> "$staging_dir/modified/nvme-driver-status.txt" + fi + else + if modinfo -k "$guest_kernel" nvme &>/dev/null; then + echo "[INFO] NVMe module exists on disk." + fi + if $fix; then + if $dry_run; then + echo "[DRYRUN] Would run: update-initramfs -u -k all" + echo "update-initramfs -u -k all" > "$staging_dir/modified/initramfs-commands.txt" + else + echo "[INFO] Adding NVMe/pci-hyperv drivers to initrd/initramfs..." + update-initramfs -u -k all + if lsinitramfs /boot/initrd.img-* | grep -q nvme; then + echo "[INFO] NVMe driver added successfully." + else + echo "[ERROR] Failed to add NVMe driver to initrd/initramfs." + fi + fi + else + echo "[ERROR] NVMe driver not found in initrd/initramfs." + fi + fi + ;; + redhat|rhel|centos|rocky|almalinux|azurelinux|mariner|suse|sles|ol) + # Check ALL installed initramfs images, not just the running kernel + _nvme_missing=false + for _img in /boot/initramfs-*.img; do + [ -f "$_img" ] || continue + [[ "$_img" == *kdump* ]] && continue + [[ "$_img" == *rescue* ]] && continue + if ! lsinitrd "$_img" 2>/dev/null | grep -q nvme; then + echo "[WARNING] NVMe driver not found in $_img" + _nvme_missing=true + fi + if ! lsinitrd "$_img" 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then + echo "[WARNING] pci-hyperv/hv_pci driver not found in $_img (required for Azure NVMe)" + _nvme_missing=true + fi + done + if ! $_nvme_missing; then + echo "[INFO] NVMe and pci-hyperv drivers found in initrd/initramfs." + if $dry_run && $fix; then + echo "[DRYRUN] NVMe and pci-hyperv drivers already in all initramfs images. No changes needed." + echo "nvme_in_initramfs=true" > "$staging_dir/modified/nvme-driver-status.txt" + echo "kernel=$(guest_kernel_version)" >> "$staging_dir/modified/nvme-driver-status.txt" + fi + else + if modinfo -k "$guest_kernel" nvme &>/dev/null; then + echo "[INFO] NVMe module exists on disk but is not in all initramfs images." + fi + if $fix; then + if $dry_run; then + echo "[DRYRUN] Would run: dracut -f --regenerate-all (with nvme nvme-core in /etc/dracut.conf.d/nvme.conf)" + echo 'add_drivers+=" nvme nvme-core pci-hyperv "' > "$staging_dir/modified/dracut-nvme.conf" + echo "dracut -f --regenerate-all" >> "$staging_dir/modified/initramfs-commands.txt" + else + echo "[INFO] Adding NVMe driver to initrd/initramfs (all kernels)..." + mkdir -p /etc/dracut.conf.d + echo 'add_drivers+=" nvme nvme-core pci-hyperv "' | tee /etc/dracut.conf.d/nvme.conf > /dev/null + dracut -f --regenerate-all + _verify_ok=true + for _img in /boot/initramfs-*.img; do + [ -f "$_img" ] || continue + [[ "$_img" == *kdump* ]] && continue + [[ "$_img" == *rescue* ]] && continue + if ! lsinitrd "$_img" 2>/dev/null | grep -q nvme; then + echo "[ERROR] NVMe driver still missing in $_img after rebuild." + _verify_ok=false + fi + if ! lsinitrd "$_img" 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then + echo "[ERROR] pci-hyperv/hv_pci driver still missing in $_img after rebuild." + _verify_ok=false + fi + done + if $_verify_ok; then + echo "[INFO] NVMe driver added successfully." + else + echo "[ERROR] Failed to add NVMe driver to all initramfs images." + fi + fi + else + echo "[ERROR] NVMe driver not found in initrd/initramfs." + fi + fi + ;; + *) + echo "[ERROR] Unsupported distribution for NVMe driver check." + return 1 + ;; + esac +} + +# Function to check nvme_core.io_timeout parameter +nvme_timeout_entries_ready() { + awk ' + /^[[:space:]]*linux(efi|16)?[[:space:]]+/ { + seen = 1 + count = 0 + for (i = 1; i <= NF; i++) { + if ($i ~ /^nvme_core[.]io_timeout=/) { + count++ + if ($i != "nvme_core.io_timeout=240") bad = 1 + } + } + if (count != 1) bad = 1 + } + END { exit !(seen && !bad) } + ' "$1" +} + +set_rhel7_timeout_defaults() { + if ! grep -q '^GRUB_CMDLINE_LINUX="' "$1"; then + echo "[ERROR] Expected quoted GRUB_CMDLINE_LINUX in $1." + return 1 + fi + if ! sed -i -E '/^GRUB_CMDLINE_LINUX="/ { s/(^|[[:space:]"])nvme_core[.]io_timeout=[^[:space:]"]+/\1/g; s/^(GRUB_CMDLINE_LINUX=")/\1nvme_core.io_timeout=240 /; }' "$1"; then + echo "[ERROR] Failed to update timeout defaults in $1." + return 1 + fi +} + +check_nvme_timeout() { + echo "[INFO] Checking nvme_core.io_timeout parameter..." + + local _rhel7_efi_config="" + case "$distro" in + redhat|rhel|centos) + if [ -r /etc/os-release ] && + ( . /etc/os-release; [ "${VERSION_ID%%.*}" = 7 ] ) && + { [ -e /etc/grub2-efi.cfg ] || [ -L /etc/grub2-efi.cfg ]; }; then + if ! _rhel7_efi_config=$(readlink -e /etc/grub2-efi.cfg); then + echo "[ERROR] Cannot resolve guest EFI configuration /etc/grub2-efi.cfg." + return 1 + fi + case "$_rhel7_efi_config" in + /boot/efi/EFI/*/grub.cfg) ;; + *) echo "[ERROR] Unsupported guest EFI configuration: $_rhel7_efi_config"; return 1 ;; + esac + # Older RHEL EFI uses a full config, not the modern redirect stub. + if ! grep -Eq '^[[:space:]]*linux(efi|16)?[[:space:]]+' "$_rhel7_efi_config"; then + echo "[ERROR] Expected standalone kernel entries in $_rhel7_efi_config; refusing to overwrite." + return 1 + fi + fi + ;; + esac + + # Build grub file list dynamically for verification + _grub_check_files="/etc/default/grub" + if [ -f /boot/grub2/grub.cfg ]; then + _grub_check_files="$_grub_check_files /boot/grub2/grub.cfg" + elif [ -f /boot/grub/grub.cfg ]; then + _grub_check_files="$_grub_check_files /boot/grub/grub.cfg" + fi + + if { [ -n "$_rhel7_efi_config" ] && nvme_timeout_entries_ready "$_rhel7_efi_config"; } || + { [ -z "$_rhel7_efi_config" ] && grep -q "nvme_core.io_timeout=240" $_grub_check_files 2>/dev/null; }; then + echo "[INFO] nvme_core.io_timeout is set to 240." + if $dry_run && $fix; then + echo "[DRYRUN] nvme_core.io_timeout already set to 240. No grub changes needed." + echo "nvme_core_io_timeout=240" > "$staging_dir/modified/nvme-timeout-status.txt" + echo "status=already_configured" >> "$staging_dir/modified/nvme-timeout-status.txt" + fi + elif [ -z "$_rhel7_efi_config" ] && command -v grubby &>/dev/null && grubby --info=ALL 2>/dev/null | grep -q "nvme_core.io_timeout=240"; then + echo "[INFO] nvme_core.io_timeout is set to 240 (BLS entries)." + else + echo "[WARNING] nvme_core.io_timeout is not set to 240." + if $fix; then + if $dry_run; then + echo "[DRYRUN] Staging grub changes..." + # Find the grub config file to stage + local grub_file="" + if [ -f /etc/default/grub ]; then + grub_file="/etc/default/grub" + fi + if [ -n "$grub_file" ]; then + cp "$grub_file" "$staging_dir/original/grub" + cp "$grub_file" "$staging_dir/modified/grub" + case "$distro" in + ubuntu) + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" + ;; + debian) + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" + ;; + suse|sles|opensuse*) + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" + ;; + ol|azurelinux|mariner) + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" + ;; + *) + if [ -n "$_rhel7_efi_config" ]; then + set_rhel7_timeout_defaults "$staging_dir/modified/grub" || return 1 + echo "[DRYRUN] Would regenerate $_rhel7_efi_config" + else + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" + fi + ;; + esac + diff -u "$staging_dir/original/grub" "$staging_dir/modified/grub" > "$staging_dir/diffs/grub.diff" 2>&1 || true + echo "[DRYRUN] Grub diff staged in $staging_dir/diffs/grub.diff" + cat "$staging_dir/diffs/grub.diff" + # Check for BLS (BootLoaderSpec) - RHEL 8+, AlmaLinux 8+, OL 8.10+ + if grep -q "GRUB_ENABLE_BLSCFG=true" "$grub_file" 2>/dev/null; then + echo "[INFO] BLS (BootLoaderSpec) is enabled." + if command -v grubby &>/dev/null; then + echo "[DRYRUN] Would run: grubby --update-kernel=ALL --args=nvme_core.io_timeout=240" + echo "bls_enabled=true" >> "$staging_dir/modified/nvme-timeout-status.txt" + echo "grubby_available=true" >> "$staging_dir/modified/nvme-timeout-status.txt" + else + echo "[WARNING] BLS is enabled but grubby is not installed." + echo "bls_enabled=true" >> "$staging_dir/modified/nvme-timeout-status.txt" + echo "grubby_available=false" >> "$staging_dir/modified/nvme-timeout-status.txt" + fi + fi + else + echo "[DRYRUN] No grub config found to stage." + fi + else + echo "[INFO] Setting nvme_core.io_timeout to 240..." + case "$distro" in + ubuntu) + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true update-grub + ;; + debian) + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true update-grub + ;; + suse|sles|opensuse*) + if [ -f /etc/default/grub ]; then + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + else + echo "[ERROR] /etc/default/grub not found." + return 1 + fi + ;; + redhat|rhel|centos|rocky|almalinux) + if [ -f /etc/default/grub ]; then + if [ -n "$_rhel7_efi_config" ]; then + set_rhel7_timeout_defaults /etc/default/grub || return 1 + if ! GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o "$_rhel7_efi_config"; then + echo "[ERROR] Failed to regenerate $_rhel7_efi_config." + return 1 + fi + else + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + fi + # Update BLS entries if applicable (RHEL 8+, AlmaLinux 8+) + if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then + if command -v grubby &>/dev/null; then + grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" + echo "[INFO] Updated BLS entries via grubby." + fi + fi + else + echo "[ERROR] /etc/default/grub not found." + return 1 + fi + ;; + ol|azurelinux|mariner) + if [ -f /etc/default/grub ]; then + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + # Update BLS entries if applicable (OL 8.10+) + if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then + if command -v grubby &>/dev/null; then + grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" + echo "[INFO] Updated BLS entries via grubby." + fi + fi + else + echo "[ERROR] /etc/default/grub not found." + return 1 + fi + ;; + *) + echo "[ERROR] Unsupported distribution for nvme_core.io_timeout fix." + return 1 + ;; + esac + + if { [ -n "$_rhel7_efi_config" ] && nvme_timeout_entries_ready "$_rhel7_efi_config"; } || + { [ -z "$_rhel7_efi_config" ] && grep -q "nvme_core.io_timeout=240" $_grub_check_files 2>/dev/null; }; then + echo "[INFO] nvme_core.io_timeout set successfully." + elif [ -z "$_rhel7_efi_config" ] && command -v grubby &>/dev/null && grubby --info=ALL 2>/dev/null | grep -q "nvme_core.io_timeout=240"; then + echo "[INFO] nvme_core.io_timeout set successfully (BLS entries)." + else + echo "[ERROR] Failed to set nvme_core.io_timeout." + if [ -n "$_rhel7_efi_config" ]; then return 1; fi + fi + fi + else + echo "[ERROR] nvme_core.io_timeout is not set to 240." + fi + fi +} + +# Function to check /etc/fstab for deprecated device names +check_fstab() { + echo "[INFO] Checking /etc/fstab for deprecated device names..." + # NOTE: /dev/mapper/* (LVM) and PARTUUID= paths survive NVMe conversion + # because they use UUID-based addressing underneath. Only /dev/sd* and + # /dev/disk/azure/scsi* paths break when disks move from SCSI to NVMe. + if grep -Eq '/dev/sd[a-z][0-9]*|/dev/disk/azure/scsi[0-9]*/lun[0-9]*' /etc/fstab; then + if $fix; then + echo "[WARNING] /etc/fstab contains deprecated device names." + if $dry_run; then + echo "[DRYRUN] Staging fstab changes..." + cp /etc/fstab "$staging_dir/original/fstab" + + # Build modified fstab in staging directory + while read -r line; do + if [[ "$line" =~ ^[^#] ]]; then + device=$(echo "$line" | awk '{print $1}') + if [[ "$device" =~ ^/dev/sd[a-z][0-9]*$ ]]; then + uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') + if [ -n "$uuid" ]; then + newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") + echo "[DRYRUN] Would replace $device with UUID=$uuid" + echo "$newline" >> "$staging_dir/modified/fstab" + else + echo "[DRYRUN] Could not find UUID for $device. Would skip." + echo "$line" >> "$staging_dir/modified/fstab" + fi + elif [[ "$device" =~ ^/dev/disk/azure/scsi[0-9]*/lun[0-9]* ]]; then + uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') + if [ -n "$uuid" ]; then + newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") + echo "[DRYRUN] Would replace $device with UUID=$uuid" + echo "$newline" >> "$staging_dir/modified/fstab" + else + echo "[DRYRUN] Could not find UUID for $device. Would skip." + echo "$line" >> "$staging_dir/modified/fstab" + fi + else + echo "$line" >> "$staging_dir/modified/fstab" + fi + else + echo "$line" >> "$staging_dir/modified/fstab" + fi + done < /etc/fstab + + diff -u "$staging_dir/original/fstab" "$staging_dir/modified/fstab" > "$staging_dir/diffs/fstab.diff" 2>&1 || true + echo "[DRYRUN] Fstab diff staged in $staging_dir/diffs/fstab.diff" + cat "$staging_dir/diffs/fstab.diff" + else + echo "[INFO] Replacing deprecated device names in /etc/fstab with UUIDs..." + + # Create a backup of the fstab file + cp /etc/fstab /etc/fstab.bak + + # Ensure fstab.new starts fresh (avoid stale leftovers from interrupted runs) + rm -f /etc/fstab.new + + # Use sed to replace device names with UUIDs + while read -r line; do + if [[ "$line" =~ ^[^#] ]]; then + device=$(echo "$line" | awk '{print $1}') + if [[ "$device" =~ ^/dev/sd[a-z][0-9]*$ ]]; then + uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') + if [ -n "$uuid" ]; then + newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") + echo "[INFO] Replaced $device with UUID=$uuid" + echo "$newline" >> /etc/fstab.new + else + echo "[WARNING] Could not find UUID for $device. Skipping." + echo "$line" >> /etc/fstab.new + fi + elif [[ "$device" =~ ^/dev/disk/azure/scsi[0-9]*/lun[0-9]* ]]; then + uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') + if [ -n "$uuid" ]; then + newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") + echo "[INFO] Replaced $device with UUID=$uuid" + echo "$newline" >> /etc/fstab.new + else + echo "[WARNING] Could not find UUID for $device. Skipping." + echo "$line" >> /etc/fstab.new + fi + else + echo "$line" >> /etc/fstab.new + fi + else + echo "$line" >> /etc/fstab.new + fi + done < /etc/fstab + + # Replace the old fstab with the new fstab + mv /etc/fstab.new /etc/fstab + + echo "[INFO] /etc/fstab updated with UUIDs. Original fstab backed up to /etc/fstab.bak" + fi + else + echo "[ERROR] /etc/fstab contains device names causing issues switching to NVMe" + fi + else + echo "[INFO] /etc/fstab does not contain deprecated device names." + fi +} + +# Run the checks +check_azure_vm_utils +for guest_kernel in "${guest_kernels[@]}"; do + check_nvme_driver +done +check_nvme_timeout +check_fstab + +# Generate dry-run summary report +if $dry_run && $fix; then + echo "" + echo "[DRYRUN] ============================================" + echo "[DRYRUN] Summary report for $(hostname)" + echo "[DRYRUN] Distro: $distro | Kernel: $(guest_kernel_version)" + echo "[DRYRUN] Staging directory: $staging_dir" + echo "[DRYRUN] ============================================" + echo "[DRYRUN] Files in staging directory:" + find "$staging_dir" -type f | sort | while read -r f; do + echo "[DRYRUN] $f" + done + echo "[DRYRUN] ============================================" + echo "[DRYRUN] No system files were modified." +fi + +exit 0 diff --git a/src/constants.rs b/src/constants.rs index f8ffe91..31bd7d0 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -33,6 +33,7 @@ pub(crate) static HELPERS_SH_FILE: &str = include_str!("action_implementation/h pub(crate) static HELPERS_PY_FILE: &str = include_str!("action_implementation/helpers.py"); pub(crate) static INITRD_IMPL_FILE: &str = include_str!("action_implementation/initrd-impl.sh"); pub(crate) static KERNEL_IMPL_FILE: &str = include_str!("action_implementation/kernel-impl.sh"); +pub(crate) static NVME_IMPL_FILE: &str = include_str!("action_implementation/nvme-impl.sh"); pub(crate) static SAFE_EXIT_FILE: &str = include_str!("action_implementation/safe-exit.sh"); pub(crate) static SERIALCONSOLE_IMPL_FILE: &str = include_str!("action_implementation/serialconsole-impl.sh"); pub(crate) static TEST_IMPL_FILE: &str = include_str!("action_implementation/test-impl.sh"); diff --git a/src/helper.rs b/src/helper.rs index a11ba79..b384135 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -358,6 +358,12 @@ fn write_builtin_action_scripts() -> Result<()> { ) .context("Writing kernel-impl.sh failed")?; + fs::write( + format!("{}/{}", constants::ACTION_IMPL_DIR, "nvme-impl.sh"), + constants::NVME_IMPL_FILE, + ) + .context("Writing nvme-impl.sh failed")?; + fs::write( format!("{}/{}", constants::ACTION_IMPL_DIR, "safe-exit.sh"), constants::SAFE_EXIT_FILE, diff --git a/tests/nvme/README.md b/tests/nvme/README.md new file mode 100644 index 0000000..622bb05 --- /dev/null +++ b/tests/nvme/README.md @@ -0,0 +1,114 @@ +# Linux NVMe action tests + +These are offline regression tests for the built-in `nvme` action. They do not +deploy VMs, contact Azure or SSH, mount filesystems, install packages, or add +runtime health checks. Session ledgers, live deployment helpers, quota tooling +and raw cloud evidence are not part of this suite. + +## Requirements + +- Linux root, including root inside WSL, and Python 3.10+. +- Existing `/usr/sbin/chroot`, `ldd`, Bash, coreutils, grep, sed, awk, diff and + find. The runner copies the required tools and their interpreters/libraries + into disposable chroots; missing prerequisites fail the run. +- Each guest uses fake files and stubbed device/repair commands. Tests never + access real guest disks or use the rescue host's device identities. + +Non-Linux or non-root hosts skip the chroot test classes. A skipped suite is not +successful execution or live NVMe acceptance. + +## Self-contained regression suite + +From the repository root: + +```bash +sudo python3 -B -m unittest discover -s tests/nvme -p 'test_*.py' -v +``` + +The 25 tests need only this ALAR checkout, not a sibling CLI repository: + +| File | Coverage | +| --- | --- | +| [test_offline.py](test_offline.py) | Seven guest-kernel, multi-kernel, explicit swap mapping, ambiguous device, invalid/missing map and missing-kernel regressions. | +| [test_efi_timeout.py](test_efi_timeout.py) | Thirteen RHEL 7 standalone EFI regressions: stale configurations, exact/all-kernel timeout tokens, nonmutation, idempotence, broken links, redirect stubs, BIOS/modern releases and failed/ineffective generation. | +| [test_runner.py](test_runner.py) | Five harness regressions: raw success/failure evidence, equally broken scripts, unexpected success and copied shebang interpreters. | + +EFI cases extract the actual action function bodies instead of maintaining a +second copy of the timeout algorithm. + +## Optional shared-source comparison + +[run_tests.py](run_tests.py) compares 191 isolated scenarios across 12 distro IDs, +driver states, check/fix/dry-run modes, legacy release files, GRUB/BLS/udev +variants, image exclusions and missing/failing tools. It first compares shared +function bodies and fallback rules, allowing only the declared offline adapters: +installed guest kernels, explicit guest-device resolution, deferred udev reload, +and ALAR's fix default/check-only flag. + +Supply the Azure CLI extension source explicitly. It is parsed with Python's +AST, never imported. The reference used for this implementation includes the +RHEL 7 EFI correction: +[`_linux_script.py` at commit `2ac43a5b`](https://github.com/jonathanbrenes/azure-cli-extensions/blob/2ac43a5b1f338177a2da1c114cae6c674d03caec/src/nvme-conversion/azext_nvme_conversion/_linux_script.py). +An older or changed reference that fails function comparison is not equivalent +coverage and must not be silently substituted. + +```bash +stamp=$(date +%Y%m%d-%H%M%S)-$$ +sudo python3 -B tests/nvme/run_tests.py \ + --reference /path/to/azure-cli-extensions/src/nvme-conversion/azext_nvme_conversion/_linux_script.py \ + --report "/tmp/alar-nvme-${stamp}.json" \ + --evidence-dir "/tmp/alar-nvme-${stamp}-evidence" \ + --jobs 4 +``` + +Reports/evidence must be new paths outside the checkout. Workers are independent, +default to at most four, and each shell phase has a 60-second timeout. The runner +rejects unexpected exits, including equally broken scripts, and asserts that +check/dry-run leave protected guest files unchanged. + +The JSON report records completion status, actual counts, source hashes and +per-case results. Optional evidence retains both scripts, raw stdout/stderr, +exits, command transcripts, before/after contents and modes, and distro summaries. +Only comparison output is normalized; raw evidence is preserved. An incomplete +report, a printed error with exit zero, or a passing fixture is not successful +NVMe boot certification. Exit 0 means all comparisons passed; 1 means completed +comparisons failed; argument errors return 2. Setup failures also fail the run. + +## Build checks + +Use the repository's existing Rust toolchain/dependencies: + +```bash +bash -n src/action_implementation/nvme-impl.sh +cargo test --locked +cargo build --release --locked +``` + +The action is embedded and materialized through the existing built-in script +mechanism; there are no new Rust dependencies or changes to action execution, +disk discovery or ADE handling. + +## Completed live coverage and boundaries + +- The x64 campaign exercised the action, actual SCSI/NVMe boots, repeat behavior + and timeout faults. RHEL 7.9's standalone EFI correction passed real NVMe boot + and effective-timeout-240 checks after the original false-readiness failure. +- Native ARM64 GNU and static musl builds succeeded. The static candidate passed + full action phases, actual boots, runtime timeout checks, repeat and fault tests + on Ubuntu 26.04, Debian 13 and Oracle Linux 10.2 ARM64. +- Oracle Linux 8.10, 9.8 and 9.7 x64 passed full action phases, 12 actual boots, + six runtime-timeout-240 assertions, repeat and fault checks **only with a + separate temporary framework candidate**. Its patch was reverted. The + unchanged framework can still misclassify those plaintext layouts as ADE + before reaching this action; no framework fix is included in this change. +- Genuine ADE recovery with valid, missing or wrong credentials was not + live-tested. Existing ADE code was not changed. +- Reliable post-conversion SSH remains unverified. Run Command and actual boot + evidence do not certify SSH connectivity. +- Legacy SCSI-only image component tests are not NVMe conversion certification. + Windows and universal image/SKU compatibility are out of scope. + +Live results describe the tested candidates, not an automatic test run by this +suite. Full logs, candidate/source hashes and per-image evidence are retained +separately; no local machine paths, credentials or cloud resource inventories +are required to run the checked-in tests. diff --git a/tests/nvme/run_tests.py b/tests/nvme/run_tests.py new file mode 100644 index 0000000..bdc6fb9 --- /dev/null +++ b/tests/nvme/run_tests.py @@ -0,0 +1,431 @@ +"""Compare Linux NVMe preparation logic in parallel, isolated chroot fixtures. + +Requires Linux root, Python 3.10+ and existing userspace tools. The extension's +literal _LINUX_SCRIPT is read with AST, never imported. Reference and candidate +scripts run on separate fake guest filesystems with stubbed device commands; +there are no mounts, real guest disks, Azure calls or SSH connections. + +CLI: --reference PATH --report NEW_JSON [--evidence-dir NEW_DIR] [--jobs N]. +Reports and evidence must be new and outside the checkout. Completed comparisons +return 0 when all cases pass or 1 when any case fails; argparse errors return 2. +An aborted setup/run can leave an incomplete report, which is not a pass. +See the adjacent README.md for dependencies, commands and evidence schemas. +""" + +from __future__ import annotations + +import argparse +import ast +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile + + +STUB = r'''#!/bin/bash +name=${0##*/} +printf '%s %s\n' "$name" "$*" >> /commands.log +if [[ -f /fail-command && "$(< /fail-command)" == "$name" ]]; then exit 42; fi +case "$name" in + hostname) echo fixture-host ;; + uname) echo rescue-kernel ;; + modinfo|udevadm|azure-nvme-id) exit 0 ;; + lsinitramfs|lsinitrd) cat "$@" ;; + update-initramfs) + [[ -f /failed-rebuild ]] && exit 0 + for image in /boot/initrd.img-*; do echo 'nvme hv_pci' > "$image"; done ;; + dracut) + [[ -f /failed-rebuild ]] && exit 0 + for image in /boot/initramfs-*.img; do + [[ "$image" == *kdump* || "$image" == *rescue* ]] && continue + echo 'nvme hv_pci' > "$image" + done ;; + update-grub) echo generated-grub > /boot/grub/grub.cfg ;; + grub2-mkconfig) echo generated-grub > "$2" ;; + grubby) + if [[ "$1" == --info=ALL ]]; then cat /bls-args + else echo nvme_core.io_timeout=240 > /bls-args; fi ;; + findmnt) + case "${@: -1}" in + /) echo /dev/sdz1 ;; /boot) echo /dev/sdz3 ;; + /boot/efi) echo /dev/sdz4 ;; *) exit 1 ;; + esac ;; + lsblk) echo sdz ;; + blkid) + device=${@: -1} + case "$device" in + /dev/sda1|/dev/sdz1) uuid=root-uuid ;; + /dev/sda2|/dev/sdz2) uuid=swap-uuid ;; + /dev/sda3|/dev/sdz3) uuid=boot-uuid ;; + /dev/sda4|/dev/sdz4) uuid=efi-uuid ;; + /dev/sdb1|/dev/disk/azure/scsi1/lun0-part1|/dev/nvme2n5p1) uuid=data-uuid ;; + *) exit 2 ;; + esac + printf '%s: UUID="%s" TYPE="ext4"\n' "$device" "$uuid" ;; + *) exit 1 ;; +esac +''' +DISTROS = ('ubuntu', 'debian', 'redhat', 'rhel', 'centos', 'rocky', 'almalinux', + 'suse', 'sles', 'ol', 'azurelinux', 'mariner') +COMMANDS = ('hostname uname modinfo udevadm lsinitramfs lsinitrd update-initramfs ' + 'dracut update-grub grub2-mkconfig grubby findmnt lsblk blkid').split() +FSTAB = '''# Preserve unrelated and unresolved entries. +/dev/sda1 / ext4 defaults 0 1 +/dev/sda3 /boot ext4 defaults 0 2 +/dev/sda4 /boot/efi vfat defaults 0 2 +/dev/sda2 none swap sw 0 0 +/dev/sdb1 /data xfs defaults 0 2 +/dev/disk/azure/scsi1/lun0-part1 /azure-data xfs defaults 0 2 +/dev/sdc1 /unavailable xfs defaults 0 2 +UUID=stable /stable ext4 defaults 0 2 +PARTUUID=part /part ext4 defaults 0 2 +/dev/mapper/rootvg-homelv /home xfs defaults 0 2 +/dev/disk/azure/resource-part1 /mnt/resource ext4 defaults 0 2 +''' + + +@dataclass(frozen=True) +class Case: + """Immutable distro/driver/mode/scenario key used by fixtures and evidence paths.""" + distro: str + state: str + mode: str + scenario: str = 'normal' + + @property + def name(self) -> str: + """Return the stable distro/state/mode/scenario identifier and relative path.""" + return '/'.join((self.distro, self.state, self.mode, self.scenario)) + + +def write(root: Path, name: str, text: str) -> None: + """Write a UTF-8 fixture file; callers supply names relative to root.""" + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding='utf-8') + + +def copy_tool(base: Path, binary: Path, destination: Path, ancestors: tuple[Path, ...] = ()) -> None: + """Copy a tool plus its shebang interpreter or ELF libraries into a chroot. + + Resolve symlinks and recursively copy absolute script interpreters. The ancestors + chain rejects interpreter cycles; missing tools and failed ldd calls abort setup. + """ + binary = binary.resolve() + if binary in ancestors: + raise RuntimeError(f'Cyclic fixture interpreter: {binary}') + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(binary, destination) + header = binary.read_bytes().split(b'\n', 1)[0] + if header.startswith(b'#!'): + interpreter = Path(header[2:].decode().split()[0]) + if not interpreter.is_absolute(): + raise RuntimeError(f'Fixture interpreter must be absolute: {binary}') + # Recent coreutils packages use scripts with a multicall interpreter. + copy_tool(base, interpreter, base / str(interpreter).lstrip('/'), (*ancestors, binary)) + return + result = subprocess.run(['ldd', str(binary)], check=True, capture_output=True, text=True) + for library in re.findall(r'(?:=>\s+|^\s*)(/\S+)', result.stdout, re.MULTILINE): + target = base / library.lstrip('/') + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(Path(library).resolve(), target) + + +def prepare_base(base: Path) -> None: + """Build the reusable userspace base and logged synthetic device-command stubs. + + Copy existing host tools only; do not install packages or run real Azure/device + commands. Missing prerequisites raise an error before fixtures can be accepted. + """ + binaries: dict[str, Path] = {} + for tool in 'bash cat mkdir touch grep sed cp rm mv awk tee diff find sort readlink'.split(): + binary = shutil.which(tool) + if binary is None: + raise RuntimeError(f'Missing fixture tool: {tool}') + binaries[tool] = Path(binary) + for tool, binary in binaries.items(): + copy_tool(base, binary, base / 'bin' / tool) + for name in COMMANDS: + write(base, f'bin/{name}', STUB) + (base / 'bin' / name).chmod(0o755) + + +def fixture(base: Path, root: Path, case: Case, script: str, original: bool) -> None: + """Populate one private fake guest from the hard-linked userspace base. + + Case fields select driver contents, release files, boot arguments and failure + injection. original=True supplies guest-1 through uname; the candidate retains + the rescue-kernel stub to exercise installed-guest-kernel discovery. + """ + shutil.copytree(base, root, copy_function=os.link) + for directory in ('etc/default', 'etc/udev/rules.d', 'boot/grub', 'boot/grub2', + 'lib/modules/guest-1', 'dev', 'tmp'): + (root / directory).mkdir(parents=True, exist_ok=True) + for name, value in { + 'dev/null': '', 'commands.log': '', 'bls-args': '', 'run.sh': script, + 'etc/os-release': f'ID={case.distro}\n', + 'etc/default/grub': 'GRUB_CMDLINE_LINUX_DEFAULT="quiet"\nGRUB_CMDLINE_LINUX="console=ttyS0"\nGRUB_ENABLE_BLSCFG=true\n', + 'etc/fstab': FSTAB, 'etc/fstab.new': 'stale interrupted content\n', + 'device-map': '/dev/sdb /dev/nvme2n5\n/dev/disk/azure/scsi1/lun0 /dev/nvme2n5\n', + 'lib/modules/guest-1/modules.builtin': 'kernel/drivers/nvme/host/nvme.ko\n' if case.state == 'builtin' else '', + }.items(): + write(root, name, value) + contents = {'missing': '', 'builtin': '', 'ready': 'nvme hv_pci', + 'no-hvpci': 'nvme', 'no-nvme': 'hv_pci'}[case.state] + for image in ('initrd.img-guest-1', 'initramfs-guest-1.img', 'initramfs-guest-2.img'): + write(root, f'boot/{image}', contents + '\n') + for image in ('initramfs-kdump.img', 'initramfs-rescue.img'): + write(root, f'boot/{image}', 'excluded\n') + if original: + (root / 'bin/uname').unlink() + write(root, 'bin/uname', '#!/bin/bash\necho guest-1\n') + (root / 'bin/uname').chmod(0o755) + scenario = case.scenario + if scenario == 'no-grubby': + (root / 'bin/grubby').unlink() + elif scenario in ('bls-ready', 'defaults-ready', 'grub2-ready', 'grub-ready'): + target = {'bls-ready': 'bls-args', 'defaults-ready': 'etc/default/grub', + 'grub2-ready': 'boot/grub2/grub.cfg', 'grub-ready': 'boot/grub/grub.cfg'}[scenario] + with (root / target).open('a') as stream: + stream.write('\nnvme_core.io_timeout=240\n') + elif scenario.startswith('utils-'): + write(root, 'bin/azure-nvme-id', STUB) + (root / 'bin/azure-nvme-id').chmod(0o755) + if scenario != 'utils-missing-rules': + directory = {'utils-etc': 'etc', 'utils-lib': 'lib', 'utils-usrlib': 'usr/lib'}[scenario] + write(root, f'{directory}/udev/rules.d/80-azure-disk.rules', '') + elif scenario == 'fallback-ready': + write(root, 'etc/udev/rules.d/99-azure-nvme-fallback.rules', 'existing rule\n') + elif scenario == 'no-grub-file': + (root / 'etc/default/grub').unlink() + elif scenario == 'failed-rebuild': + write(root, 'failed-rebuild', '') + elif scenario.startswith('fail-'): + command = {'fail-update': 'update-initramfs', 'fail-dracut': 'dracut', 'fail-grub': 'grub2-mkconfig'}[scenario] + write(root, 'fail-command', command) + elif scenario == 'no-fstab-changes': + write(root, 'etc/fstab', 'UUID=stable / ext4 defaults 0 1\n') + elif scenario == 'no-release' or scenario.startswith('legacy-'): + (root / 'etc/os-release').unlink() + if scenario.startswith('legacy-'): + write(root, f'etc/{scenario.removeprefix("legacy-")}', '') + + +def normalized(text: str) -> str: + """Remove only declared offline diagnostics, diff timestamps and check-flag usage. + + Use this for comparisons, never for the retained raw stdout/stderr evidence. + """ + text = re.sub(r'^\[INFO\] Offline guest:.*\n|^\[WARNING\] Cannot map guest device .*\n', '', text, flags=re.MULTILINE) + text = re.sub(r'^(--- |\+\+\+ )([^\t\n]+)\t[^\n]*', r'\1\2', text, flags=re.MULTILINE) + return text.replace('[-check] ', '') + + +def snapshot(root: Path, normalize_content: bool = True) -> dict[str, tuple[int, str]]: + """Capture fixture text and permission bits beneath etc, boot and tmp. + + normalize_content=False retains literal text for raw before/after evidence; + the default applies only the declared comparison normalization. + """ + return {str(path.relative_to(root)): (path.stat().st_mode & 0o7777, + normalized(path.read_text()) if normalize_content else path.read_text()) + for directory in ('etc', 'boot', 'tmp') for path in (root / directory).rglob('*') + if path.is_file()} + + +def compare(base: Path, parent: Path, case: Case, reference: str, action: str, + evidence_directory: Path | None = None) -> dict[str, str]: + """Run and validate both scripts for one case, returning passed/failed details. + + Each chroot phase has a 60-second timeout and an independently expected exit, + so equally broken scripts cannot pass by equality alone. Compare normalized + output, guest files, BLS arguments, mapping behavior and check/dry-run nonmutation. + When evidence_directory is supplied, write a new schema-version-1 trace with + raw streams, commands and literal snapshots, including caught partial failures. + Existing evidence files are rejected rather than overwritten. + """ + phases: list[dict[str, object]] = [] + trace: dict[str, object] = {'schema_version': 1, 'kind': 'offline-stub-fixture', + 'case': case.name, 'phases': phases, 'boot_evidence': False} + try: + with tempfile.TemporaryDirectory(dir=parent, prefix='case-') as temporary: + roots = [Path(temporary) / name for name in ('original', 'action')] + outputs = [] + for index, (root, script) in enumerate(zip(roots, (reference, action))): + fixture(base, root, case, script, original=index == 0) + before = {name: value for name, value in snapshot(root).items() if not name.startswith('tmp/')} + args = {'fix': ['-fix'] if index == 0 else [], + 'check': [] if index == 0 else ['-check'], + 'dryrun': ['-dryrun'], 'invalid': ['-invalid']}[case.mode] + command = ['/usr/sbin/chroot', str(root), '/bin/bash', '/run.sh', *args] + phase: dict[str, object] = {'script': 'original' if index == 0 else 'candidate', + 'command': command, 'before': snapshot(root, False)} + phases.append(phase) + result = subprocess.run(command, + env={'PATH': '/bin', 'ALAR_NVME_DEVICE_MAP': '/device-map'}, + capture_output=True, text=True, timeout=60) + phase.update({'returncode': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr, + 'after': snapshot(root, False), 'commands': (root / 'commands.log').read_text()}) + expected_exit = 1 if case.mode == 'invalid' or case.scenario == 'no-release' else 0 + if result.returncode != expected_exit: + raise AssertionError(f'Unexpected script exit {result.returncode}; expected {expected_exit}: ' + f'{result.stdout}{result.stderr}') + outputs.append((result.returncode, normalized(result.stdout + result.stderr))) + if case.mode in ('check', 'dryrun'): + after = {name: value for name, value in snapshot(root).items() if not name.startswith('tmp/')} + if before != after: + raise AssertionError(f'{case.mode} modified protected guest files') + if outputs[0] != outputs[1]: + raise AssertionError(f'Original output: {outputs[0]}\nCandidate output: {outputs[1]}') + if snapshot(roots[0]) != snapshot(roots[1]): + raise AssertionError('Guest configuration, image or dry-run artifacts differ') + if (roots[0] / 'bls-args').read_bytes() != (roots[1] / 'bls-args').read_bytes(): + raise AssertionError('BLS arguments differ') + log = (roots[1] / 'commands.log').read_text() + if re.search(r'^lsinitrd .*?(kdump|rescue)|^uname |^blkid -c /dev/null /dev/sd[abc]', log, re.MULTILINE): + raise AssertionError('Rescue identity used or excluded image inspected') + if case.mode == 'fix' and case.scenario == 'normal': + fstab = (roots[1] / 'etc/fstab').read_text() + for expected in ('UUID=swap-uuid none swap', 'UUID=data-uuid /data', + 'UUID=data-uuid /azure-data', '/dev/sdc1 /unavailable'): + if expected not in fstab: + raise AssertionError(f'Missing fstab assertion: {expected}') + outcome = {'case': case.name, 'status': 'passed'} + except (OSError, ValueError, AssertionError, subprocess.SubprocessError) as error: + outcome = {'case': case.name, 'status': 'failed', 'error': str(error)} + if evidence_directory is not None: + path = evidence_directory / f'{case.name}.json' + path.parent.mkdir(parents=True, exist_ok=True) + trace.update({'result': outcome, 'completed_at': datetime.now(timezone.utc).isoformat()}) + with path.open('x', encoding='utf-8') as stream: + json.dump(trace, stream, indent=2) + return outcome + + +def matrix() -> list[Case]: + """Return the 191 distro/driver/mode/fallback/error regression cases.""" + cases = [Case(distro, state, mode) for distro in DISTROS + for state in ('missing', 'ready', 'builtin') for mode in ('fix', 'check', 'dryrun')] + cases += [Case(distro, state, mode) for distro in ('ubuntu', 'rhel') + for state in ('no-hvpci', 'no-nvme') for mode in ('fix', 'check', 'dryrun')] + scenarios = ('no-grubby', 'bls-ready', 'defaults-ready', 'grub2-ready', 'grub-ready', + 'utils-missing-rules', 'utils-etc', 'utils-lib', 'utils-usrlib', 'fallback-ready', + 'no-grub-file', 'failed-rebuild', 'fail-dracut', 'fail-grub', 'no-fstab-changes') + cases += [Case('rhel', 'missing', mode, scenario) for scenario in scenarios for mode in ('fix', 'check', 'dryrun')] + cases += [Case('ubuntu', 'missing', mode, scenario) for scenario in ('failed-rebuild', 'fail-update') for mode in ('fix', 'check', 'dryrun')] + cases += [Case('ignored', 'missing', mode, f'legacy-{release}') + for release in ('debian_version', 'SuSE-release', 'redhat-release', 'centos-release', 'rocky-release') + for mode in ('fix', 'check', 'dryrun')] + cases += [Case('arch', 'missing', mode) for mode in ('fix', 'check', 'dryrun')] + return cases + [Case('ignored', 'missing', 'fix', 'no-release'), Case('ubuntu', 'missing', 'invalid')] + + +def verify_functions(reference: str, action: str) -> None: + """Reject changes beyond declared offline adapters in original shell functions. + + Compare original and shared timeout helper function bodies and the complete fallback udev rule literally, + allowing only the named guest-kernel/device/udev/usage adaptations. + """ + for name in ('setup_dryrun', 'usage', 'check_azure_vm_utils', '_install_fallback_udev_rules', + 'check_nvme_driver', 'nvme_timeout_entries_ready', 'set_rhel7_timeout_defaults', + 'check_nvme_timeout', 'check_fstab'): + bodies = [] + for script in (reference, action): + match = re.search(rf'^{name}\(\) \{{\n.*?^\}}', script, re.MULTILINE | re.DOTALL) + if match is None: + raise ValueError(f'Missing original function: {name}') + bodies.append('\n'.join(line for line in match[0].splitlines() + if not line.lstrip().startswith('#') and 'echo "Usage:' not in line)) + expected = bodies[0].replace('uname -r', 'guest_kernel_version').replace('modinfo nvme', 'modinfo -k "$guest_kernel" nvme') + expected = expected.replace('blkid "$device"', 'guest_blkid "$device"').replace( + 'udevadm control --reload-rules 2>/dev/null || true', + 'echo "[INFO] Offline guest: udev rules will load at the next boot."') + if expected != bodies[1]: + raise ValueError(f'Original function differs beyond offline adapters: {name}') + rules = [re.search(r"^_FALLBACK_UDEV_RULE=.*?^LABEL=.*?'$", text, re.MULTILINE | re.DOTALL) for text in (reference, action)] + if any(rule is None for rule in rules) or [rule[0] for rule in rules if rule is not None][0] != [rule[0] for rule in rules if rule is not None][1]: + raise ValueError('Fallback udev rules differ') + + +def main() -> int: + """Validate CLI paths, run bounded fixture workers and write the final report. + + Extract the reference literal without importing its module. Create an incomplete + report first; only a finished run records completed status, hashes, host details + and sorted case results. Optional evidence adds script copies, per-case traces + and per-distro summaries. Return 1 for completed runs with failed comparisons. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--reference', type=Path, required=True, help='Original extension _linux_script.py; read, never imported.') + parser.add_argument('--report', type=Path, required=True, help='New JSON report outside the checkout.') + parser.add_argument('--evidence-dir', type=Path, help='New external directory for raw per-case and per-distro evidence.') + parser.add_argument('--jobs', type=int, default=min(4, os.cpu_count() or 1)) + args = parser.parse_args() + if sys.platform != 'linux' or os.geteuid() != 0: + parser.error('Run as root inside Linux/WSL; fixtures use isolated chroot directories without mounts.') + if args.jobs < 1: + parser.error('--jobs must be positive') + report = args.report.resolve() + if report.is_relative_to(Path(__file__).resolve().parents[2]): + parser.error('Keep generated reports outside the checkout') + evidence = args.evidence_dir.resolve() if args.evidence_dir is not None else None + if evidence is not None and evidence.is_relative_to(Path(__file__).resolve().parents[2]): + parser.error('Keep raw evidence outside the checkout') + tree = ast.parse(args.reference.resolve().read_text(encoding='utf-8')) + values = [ast.literal_eval(node.value) for node in tree.body if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == '_LINUX_SCRIPT' for target in node.targets)] + if len(values) != 1 or not isinstance(values[0], str): + parser.error('Reference must define one literal _LINUX_SCRIPT string') + reference = values[0] + action = (Path(__file__).resolve().parents[2] / 'src/action_implementation/nvme-impl.sh').read_text() + verify_functions(reference, action) + report.parent.mkdir(parents=True, exist_ok=True) + with report.open('x', encoding='utf-8') as stream: + json.dump({'schema_version': 1, 'status': 'incomplete', 'mode': 'offline-fixtures'}, stream) + if evidence is not None: + evidence.mkdir(parents=True, exist_ok=False) + (evidence / 'original-linux-script.sh').write_text(reference, encoding='utf-8') + (evidence / 'candidate-nvme-impl.sh').write_text(action, encoding='utf-8') + results = [] + with tempfile.TemporaryDirectory(prefix='alar-nvme-tests-') as temporary: + parent = Path(temporary) + prepare_base(parent / 'base') + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + futures = [pool.submit(compare, parent / 'base', parent, case, reference, action, evidence) for case in matrix()] + for future in as_completed(futures): + result = future.result() + results.append(result) + if result['status'] == 'failed': + print(f"FAIL {result['case']}: {result['error']}", file=sys.stderr) + failed = sum(result['status'] == 'failed' for result in results) + document = {'schema_version': 1, 'status': 'completed', 'mode': 'offline-fixtures', 'completed_at': datetime.now(timezone.utc).isoformat(), + 'workers': args.jobs, 'total': len(results), 'passed': len(results) - failed, 'failed': failed, + 'original_functions_match': True, 'action_sha256': hashlib.sha256(action.encode()).hexdigest(), + 'reference_sha256': hashlib.sha256(reference.encode()).hexdigest(), 'results': sorted(results, key=lambda row: row['case']), + 'evidence_directory': str(evidence) if evidence is not None else None, + 'execution_host': {'wsl_distribution': os.environ.get('WSL_DISTRO_NAME'), 'python': sys.version, + 'os_release': Path('/etc/os-release').read_text()}} + if evidence is not None: + for distro in sorted({row['case'].split('/')[0] for row in results}): + rows = [row for row in document['results'] if row['case'].split('/')[0] == distro] + summary = {'kind': 'offline-stub-fixture-distro-summary', 'distro_id': distro, + 'execution_host': document['execution_host'], 'action_sha256': document['action_sha256'], + 'reference_sha256': document['reference_sha256'], 'results': rows, + 'raw_case_files': [f"{row['case']}.json" for row in rows], 'live_status': 'not run'} + with (evidence / f'{distro}.json').open('x', encoding='utf-8') as stream: + json.dump(summary, stream, indent=2) + report.write_text(json.dumps(document, indent=2) + '\n', encoding='utf-8') + print(f"{len(results) - failed}/{len(results)} passed; {args.jobs} parallel workers; report: {report}") + return int(failed != 0) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/nvme/test_efi_timeout.py b/tests/nvme/test_efi_timeout.py new file mode 100644 index 0000000..44a1c1a --- /dev/null +++ b/tests/nvme/test_efi_timeout.py @@ -0,0 +1,152 @@ +"""Regress ALAR's RHEL 7 standalone EFI timeout handling in fake chroots. + +Linux root required; uses existing copied tools, never Azure, real mounts or disks. +Each case exercises the actual action's timeout function and helper bodies. +""" +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from run_tests import prepare_base, write + + +@unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required') +class EfiTimeoutTests(unittest.TestCase): + """Keep stale EFI/defaults, exact token checks and other loader layouts safe.""" + @classmethod + def setUpClass(cls): + """Read the repository action and copy existing userspace tools.""" + cls.tmp = tempfile.TemporaryDirectory(prefix='alar-efi-timeout-') + cls.addClassCleanup(cls.tmp.cleanup) + cls.base = Path(cls.tmp.name) / 'base' + prepare_base(cls.base) + repo = Path(__file__).resolve().parents[2] + cls.scripts = ((repo / 'src/action_implementation/nvme-impl.sh').read_text(),) + + def run_case(self, script, mode='fix', version='7.9', efi=True, ready=False, + token='', broken=False, redirect=False, failure=False, missing_defaults=False, silent_failure=False, other_kernel_missing=False): + """Run actual function definitions against synthetic boot entries and logged rebuilds.""" + temporary = tempfile.TemporaryDirectory(dir=self.tmp.name) + self.addCleanup(temporary.cleanup) + root = Path(temporary.name) / 'guest' + shutil.copytree(self.base, root) + target = '/boot/efi/EFI/redhat/grub.cfg' + write(root, 'etc/os-release', f'ID=rhel\nVERSION_ID="{version}"\n') + defaults = 'GRUB_CMDLINE_LINUX="quiet nvme_core.io_timeout=240 console=ttyS0"\n' + if not missing_defaults: + write(root, 'etc/default/grub', defaults) + entry = 'linuxefi /vmlinuz root=/dev/mapper/rootvg-rootlv quiet console=ttyS0' + write(root, 'boot/grub2/grub.cfg', entry + ' nvme_core.io_timeout=240\n') + if efi: + write(root, target.lstrip('/'), 'configfile /boot/grub2/grub.cfg\n' if redirect else + entry + (' nvme_core.io_timeout=240' if ready else (' ' + token if token else '')) + '\n' + (entry.replace('/vmlinuz', '/vmlinuz-older') + '\n' if other_kernel_missing else '')) + (root / 'etc/grub2-efi.cfg').symlink_to('/boot/efi/EFI/redhat/missing.cfg' if broken else target) + write(root, 'bin/grub2-mkconfig', '#!/bin/bash\necho "grub2-mkconfig $*" >> /commands.log\n' + + ('echo rebuild-error >&2; exit 42\n' if failure else 'exit 0\n' if silent_failure else + '. /etc/default/grub\nprintf "linuxefi /vmlinuz root=/dev/mapper/rootvg-rootlv %s\\n" "$GRUB_CMDLINE_LINUX" > "$2"\n')) + (root / 'bin/grub2-mkconfig').chmod(0o755) + write(root, 'commands.log', '') + write(root, 'dev/null', '') + for directory in ('tmp/staging/original', 'tmp/staging/modified', 'tmp/staging/diffs'): + (root / directory).mkdir(parents=True, exist_ok=True) + functions = '\n\n'.join(re.findall(r'^(?:nvme_timeout_entries_ready|set_rhel7_timeout_defaults|check_nvme_timeout)\(\) \{\n.*?^\}', script, re.MULTILINE | re.DOTALL)) + write(root, 'run.sh', functions + '\ndistro=rhel\nfix=' + ('false' if mode == 'check' else 'true') + + '\ndry_run=' + ('true' if mode == 'dryrun' else 'false') + + '\nstaging_dir=/tmp/staging\ncheck_nvme_timeout\n') + before = {str(path.relative_to(root)): path.read_bytes() for path in (root / 'boot').rglob('*') if path.is_file()} + result = subprocess.run(['/usr/sbin/chroot', str(root), '/bin/bash', '/run.sh'], + env={'PATH': '/bin'}, text=True, capture_output=True, timeout=30) + return root, result, before + + def each_source(self, **kwargs): + """Exercise the repository action, not a copied timeout algorithm.""" + return [self.run_case(script, **kwargs) for script in self.scripts] + + def test_stale_efi_is_not_ready_from_defaults_or_other_config(self): + """The exact live failure must not report readiness from the wrong files.""" + for root, result, _ in self.each_source(mode='check'): + self.assertIn('[ERROR] nvme_core.io_timeout is not set to 240.', result.stdout) + self.assertNotIn('[INFO] nvme_core.io_timeout is set to 240.', result.stdout) + + def test_fix_rebuilds_standalone_efi_without_duplicate_default_argument(self): + """Repair the proven standalone EFI target even when desired defaults already have 240.""" + for root, result, _ in self.each_source(): + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg', (root/'commands.log').read_text()) + self.assertEqual((root/'etc/default/grub').read_text().count('nvme_core.io_timeout=240'), 1) + self.assertIn('quiet', (root/'etc/default/grub').read_text()) + self.assertIn('nvme_core.io_timeout=240', (root/'boot/efi/EFI/redhat/grub.cfg').read_text()) + + def test_ready_standalone_efi_is_idempotent(self): + """A ready EFI entry skips a needless rewrite.""" + for root, result, _ in self.each_source(ready=True): + self.assertNotIn('grub2-mkconfig', (root/'commands.log').read_text()) + self.assertIn('is set to 240.', result.stdout) + + def test_partial_or_wrong_argument_is_not_ready(self): + """2400 and a conflicting timeout must not be accepted as 240.""" + for token in ('nvme_core.io_timeout=2400', 'nvme_core.io_timeout=240 nvme_core.io_timeout=30'): + for root, result, _ in self.each_source(mode='check', token=token): + self.assertIn('[ERROR] nvme_core.io_timeout is not set to 240.', result.stdout) + + def test_dryrun_does_not_change_boot_files(self): + """Stage defaults and target diagnostics without rebuilding real fixture files.""" + for root, result, before in self.each_source(mode='dryrun'): + after = {str(path.relative_to(root)): path.read_bytes() for path in (root/'boot').rglob('*') if path.is_file()} + self.assertEqual(before, after) + self.assertIn('/boot/efi/EFI/redhat/grub.cfg', result.stdout) + self.assertNotIn('grub2-mkconfig', (root/'commands.log').read_text()) + + def test_broken_efi_target_is_explicit_error(self): + """A broken configured EFI link must not fall through to false readiness.""" + for root, result, _ in self.each_source(broken=True): + self.assertNotEqual(result.returncode, 0) + self.assertIn('[ERROR]', result.stdout) + self.assertEqual((root/'commands.log').read_text(), '') + + def test_modern_redirect_is_never_overwritten(self): + """A configfile stub must not become a full generated configuration.""" + for root, result, before in self.each_source(redirect=True): + self.assertNotEqual(result.returncode, 0) + self.assertIn('[ERROR]', result.stdout) + self.assertEqual((root/'boot/efi/EFI/redhat/grub.cfg').read_bytes(), before['boot/efi/EFI/redhat/grub.cfg']) + + def test_modern_release_keeps_original_behavior(self): + """RHEL8+/BLS selection remains outside this targeted old standalone EFI path.""" + for root, result, _ in self.each_source(version='9.8', redirect=True): + self.assertEqual(result.returncode, 0) + self.assertIn('is set to 240.', result.stdout) + self.assertEqual((root/'commands.log').read_text(), '') + + def test_bios_layout_keeps_original_behavior(self): + """Without a guest EFI configuration link retain the existing BIOS path.""" + for root, result, _ in self.each_source(efi=False): + self.assertEqual(result.returncode, 0) + self.assertIn('is set to 240.', result.stdout) + + def test_failed_efi_rebuild_is_error(self): + """An actual failed generator must not be hidden by desired defaults.""" + for root, result, _ in self.each_source(failure=True): + self.assertNotEqual(result.returncode, 0) + self.assertIn('[ERROR]', result.stdout) + + def test_missing_defaults_is_error(self): + """The fix cannot silently succeed without its expected defaults file.""" + for root, result, _ in self.each_source(missing_defaults=True): + self.assertNotEqual(result.returncode, 0) + self.assertIn('[ERROR]', result.stdout) + + def test_every_standalone_kernel_entry_requires_timeout(self): + """One ready entry cannot mask an older kernel without the required flag.""" + for root, result, _ in self.each_source(mode='check', token='nvme_core.io_timeout=240', other_kernel_missing=True): + self.assertIn('[ERROR] nvme_core.io_timeout is not set to 240.', result.stdout) + + def test_successful_generator_without_repair_is_rejected(self): + """An exit-zero generator that leaves stale EFI entries is not a successful fix.""" + for root, result, _ in self.each_source(silent_failure=True): + self.assertNotEqual(result.returncode, 0) + self.assertIn('[ERROR] Failed to set nvme_core.io_timeout.', result.stdout) diff --git a/tests/nvme/test_offline.py b/tests/nvme/test_offline.py new file mode 100644 index 0000000..5eae258 --- /dev/null +++ b/tests/nvme/test_offline.py @@ -0,0 +1,116 @@ +"""Seven regressions for ALAR's offline guest-kernel and device-map adapters. + +Run through unittest discovery as Linux root with the same copied-tool/chroot +prerequisites as run_tests.py. Other hosts skip this class, not certify it. +Tests use private fake guest directories, stub commands and the repository +candidate; they do not import the reference or use real disks/mounts/Azure/SSH. +See the adjacent README.md for the combined suite command and coverage. +""" + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +from run_tests import Case, fixture, prepare_base, write + + +@unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required for isolated chroot fixtures') +class OfflineTests(unittest.TestCase): + """Verify guest identity, all kernels, safe swap mapping and explicit failures.""" + @classmethod + def setUpClass(cls): + """Create a shared temporary userspace base and read the candidate shell source.""" + cls.temporary = tempfile.TemporaryDirectory(prefix='alar-nvme-adapters-') + cls.addClassCleanup(cls.temporary.cleanup) + cls.base = Path(cls.temporary.name) / 'base' + prepare_base(cls.base) + cls.action = (Path(__file__).resolve().parents[2] / 'src/action_implementation/nvme-impl.sh').read_text() + + def setUp(self): + """Allocate a separate guest directory with automatic cleanup for each test.""" + self.directory = tempfile.TemporaryDirectory(dir=self.temporary.name) + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) / 'guest' + + def prepare(self, distro='rhel', state='missing'): + """Build the selected fake guest layout for default-fix candidate execution.""" + fixture(self.base, self.root, Case(distro, state, 'fix'), self.action, original=False) + + def run_action(self, mapping='/device-map'): + """Execute the candidate in the test chroot with a 60-second timeout. + + mapping names a guest-visible map file; None omits ALAR_NVME_DEVICE_MAP entirely. + Return captured status/streams so tests can assert diagnostics and command use. + """ + environment = {'PATH': '/bin'} + if mapping is not None: + environment['ALAR_NVME_DEVICE_MAP'] = mapping + return subprocess.run(['/usr/sbin/chroot', str(self.root), '/bin/bash', '/run.sh'], + env=environment, capture_output=True, text=True, timeout=60) + + def log(self): + """Read the stub-command transcript from the current fake guest.""" + return (self.root / 'commands.log').read_text() + + def test_guest_builtin_kernel_not_rescue_kernel(self): + """A guest built-in driver must skip rebuilding without consulting rescue uname.""" + self.prepare('ubuntu', 'builtin') + result = self.run_action() + self.assertIn('NVMe driver is built into the kernel.', result.stdout) + self.assertNotIn('uname ', self.log()) + self.assertNotIn('update-initramfs ', self.log()) + + def test_all_guest_kernels_are_checked(self): + """A second installed guest kernel must be checked and repaired when needed.""" + self.prepare(state='builtin') + write(self.root, 'lib/modules/guest-2/modules.builtin', '') + self.run_action() + self.assertIn('modinfo -k guest-2 nvme', self.log()) + self.assertIn('dracut -f --regenerate-all', self.log()) + + def test_explicit_partition_mapping_covers_unmounted_swap(self): + """An explicit guest/rescue partition pair must resolve an unmounted swap entry.""" + self.prepare() + write(self.root, 'device-map', '/dev/sda2 /dev/nvme2n5p1\n') + self.run_action() + self.assertIn('UUID=data-uuid none swap', (self.root / 'etc/fstab').read_text()) + + def test_ambiguous_swap_is_not_looked_up_on_rescue_host(self): + """Unresolved swap must remain intact without probing its old name on the rescue.""" + self.prepare() + write(self.root, 'etc/fstab', 'UUID=stable / ext4 defaults 0 1\n/dev/sda2 none swap sw 0 0\n') + result = self.run_action(mapping=None) + self.assertIn('Cannot map guest device /dev/sda2', result.stderr) + self.assertIn('/dev/sda2 none swap', (self.root / 'etc/fstab').read_text()) + self.assertNotIn('blkid -c /dev/null /dev/sda2', self.log()) + + def test_invalid_map_is_reported_without_device_guessing(self): + """Malformed mapping must emit an error without speculative blkid calls.""" + self.prepare() + write(self.root, 'device-map', 'invalid-map\n') + result = self.run_action() + self.assertIn('[ERROR] Invalid device map entry:', result.stderr) + self.assertNotIn('blkid ', self.log()) + + def test_missing_map_is_reported(self): + """An unreadable explicitly selected map must emit a diagnostic.""" + self.prepare() + result = self.run_action(mapping='/missing-map') + self.assertIn('[ERROR] Cannot read device map:', result.stderr) + + def test_missing_guest_kernels_prevent_mutations(self): + """Missing installed guest kernels must fail before any stubbed repair command.""" + self.prepare() + shutil.rmtree(self.root / 'lib/modules/guest-1') + result = self.run_action() + self.assertEqual(result.returncode, 1) + self.assertIn('[ERROR] No installed guest kernels', result.stdout) + self.assertEqual(self.log(), '') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/nvme/test_runner.py b/tests/nvme/test_runner.py new file mode 100644 index 0000000..e7c6991 --- /dev/null +++ b/tests/nvme/test_runner.py @@ -0,0 +1,91 @@ +"""Five regressions for fixture validity, raw evidence and interpreter copying. + +Run with unittest discovery as Linux root and existing chroot/userspace tools. +Other hosts skip this class; that is not guest acceptance. Tests reject equally +broken scripts and unexpected successful exits, preserve raw success/failure +records, and prove a shebang tool can run with its copied interpreter/libraries. +No Azure, SSH, real guest disks or mounts are used. See the adjacent README.md. +""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +from run_tests import Case, compare, copy_tool, prepare_base, write + + +@unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required for isolated fixtures') +class RunnerTests(unittest.TestCase): + """Validate the harness and audit traces, not real Linux NVMe boot readiness.""" + def test_raw_case_evidence_keeps_streams_and_file_snapshots(self): + """Successful traces must retain both streams and literal before/after snapshots.""" + with tempfile.TemporaryDirectory(prefix='alar-raw-evidence-') as directory: + parent = Path(directory) + prepare_base(parent / 'base') + script = 'echo standard-output; echo standard-error >&2\n' + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'check'), script, script, parent / 'review') + self.assertEqual(result['status'], 'passed') + evidence = json.loads((parent / 'review/ubuntu/ready/check/normal.json').read_text()) + self.assertFalse(evidence['boot_evidence']) + self.assertEqual(len(evidence['phases']), 2) + for phase in evidence['phases']: + self.assertEqual(phase['returncode'], 0) + self.assertEqual(phase['stdout'], 'standard-output\n') + self.assertEqual(phase['stderr'], 'standard-error\n') + self.assertIn('etc/fstab', phase['before']) + self.assertEqual(phase['before'], phase['after']) + + def test_failed_case_preserves_actual_exit_in_evidence(self): + """A caught shell failure must retain its real exit and failed result in evidence.""" + with tempfile.TemporaryDirectory(prefix='alar-failed-evidence-') as directory: + parent = Path(directory) + prepare_base(parent / 'base') + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'check'), 'if then\n', 'if then\n', parent / 'review') + self.assertEqual(result['status'], 'failed') + evidence = json.loads((parent / 'review/ubuntu/ready/check/normal.json').read_text()) + self.assertEqual(evidence['phases'][0]['returncode'], 2) + self.assertEqual(evidence['result']['status'], 'failed') + + def test_equal_shell_errors_are_failures(self): + """Matching shell syntax failures must still fail the expected-exit guard.""" + with tempfile.TemporaryDirectory(prefix='alar-equal-errors-') as directory: + parent = Path(directory) + prepare_base(parent / 'base') + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'check'), 'if then\n', 'if then\n') + self.assertEqual(result['status'], 'failed') + self.assertIn('Unexpected script exit 2', result['error']) + + def test_equal_success_cannot_satisfy_expected_usage_failure(self): + """Matching exit0 results must not pass a case whose expected exit is 1.""" + with tempfile.TemporaryDirectory(prefix='alar-usage-errors-') as directory: + parent = Path(directory) + prepare_base(parent / 'base') + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'invalid'), 'exit 0\n', 'exit 0\n') + self.assertEqual(result['status'], 'failed') + self.assertIn('expected 1', result['error']) + + def test_shebang_fixture_copies_interpreter(self): + """A copied script must run in its chroot with the absolute interpreter present.""" + bash = shutil.which('bash') + self.assertIsNotNone(bash) + with tempfile.TemporaryDirectory(prefix='alar-shebang-') as directory: + parent = Path(directory) + script = parent / 'script' + script.write_text(f'#!{bash}\nprintf copied-interpreter\n') + script.chmod(0o755) + root = parent / 'root' + copy_tool(root, script, root / 'bin/probe') + write(root, 'dev/null', '') + result = subprocess.run(['/usr/sbin/chroot', str(root), '/bin/probe'], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, 'copied-interpreter') + + +if __name__ == '__main__': + unittest.main() From 38fd1ad1113df4a3fb04126e1f2a1ae0feb5ef1a Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Tue, 24 Nov 2026 20:33:01 -0600 Subject: [PATCH 2/9] Make ALAR NVMe action fix-only Remove unused check/dry-run flags, staging and non-fix branches while preserving default repairs and the optional equivalent -fix argument. Retain every shared-source fix/error scenario, update the self-contained regressions and document the narrower interface and historical live scope. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 11 +- src/action_implementation/nvme-impl.sh | 455 +++++++------------------ tests/nvme/README.md | 38 ++- tests/nvme/run_tests.py | 62 ++-- tests/nvme/test_efi_timeout.py | 35 +- tests/nvme/test_offline.py | 35 +- tests/nvme/test_runner.py | 21 +- 7 files changed, 247 insertions(+), 410 deletions(-) diff --git a/README.md b/README.md index 03abc8c..88ed797 100644 --- a/README.md +++ b/README.md @@ -86,11 +86,10 @@ Unresolved devices are left unchanged with a warning; the action does not guess that an old guest device name still identifies the same disk on the rescue VM. The original fstab backup remains `/etc/fstab.bak`. -ALAR defaults to applying fixes. Within an already prepared guest chroot, the -script also supports `bash /tmp/action_implementation/nvme-impl.sh -check` for -the original check-only behavior and `bash /tmp/action_implementation/nvme-impl.sh -dryrun` -for the original staged changes, diffs and summary under `/tmp/nvme-conversion-dryrun/`. -These script modes do not add arguments to ALAR's CLI. +ALAR always applies the conditional fixes. Within an already prepared guest +chroot, `bash /tmp/action_implementation/nvme-impl.sh -fix` is equivalent to +running the script without arguments. Check-only and dry-run modes are not +supported; no additional flags are added to ALAR's CLI. **Known framework limitation:** some Oracle Linux disk layouts are classified as ADE-encrypted before ALAR reaches the action. Oracle Linux 8.10, 9.8 and 9.7 passed @@ -99,7 +98,7 @@ that patch was reverted and is not included here. Those results do not mean the unchanged framework can process those layouts. Genuine ADE credential recovery and reliable post-conversion SSH connectivity are not certified by these tests. -The original diagnostic and exit behavior is preserved: review the action output, +The original fix-path diagnostic and exit behavior is preserved: review the action output, not just ALAR's exit status, when evaluating preparation results. The [NVMe test guide](tests/nvme/README.md) documents the self-contained regression suite, optional shared-source comparisons, completed live coverage and limits. diff --git a/src/action_implementation/nvme-impl.sh b/src/action_implementation/nvme-impl.sh index d22443f..f17e67c 100644 --- a/src/action_implementation/nvme-impl.sh +++ b/src/action_implementation/nvme-impl.sh @@ -4,7 +4,7 @@ # Licensed under the terms found in the LICENSE file in the root of this source tree. # Linux script from the nvme-conversion CLI extension, with offline guest -# kernel/device resolution and fix mode as the ALAR default. +# kernel/device resolution and fix-only behavior for ALAR. guest_kernel_version() { printf '%s\n' "$guest_kernel" @@ -95,42 +95,18 @@ guest_blkid() { command blkid -c /dev/null "$device" } -# Set default values -fix=true -dry_run=false distro="" -# Staging directory for dry-run mode -staging_dir="" - -setup_dryrun() { - staging_dir="/tmp/nvme-conversion-dryrun" - rm -rf "$staging_dir" - mkdir -p "$staging_dir/original" "$staging_dir/modified" "$staging_dir/diffs" - echo "$(hostname)" > "$staging_dir/hostname" - echo "$distro" > "$staging_dir/distro" - guest_kernel_version > "$staging_dir/kernel" - echo "[INFO] Dry-run mode: staging changes in $staging_dir" -} - # Function to display usage usage() { - echo "Usage: $0 [-check] [-fix] [-dryrun]" + echo "Usage: $0 [-fix]" exit 1 } # Parse command line arguments while [ $# -gt 0 ]; do case "$1" in - -check) - fix=false - ;; -fix) - fix=true - ;; - -dryrun) - dry_run=true - fix=true ;; *) usage @@ -169,13 +145,6 @@ if [ "${#guest_kernels[@]}" -eq 0 ]; then echo "[ERROR] No installed guest kernels found in /lib/modules." exit 1 fi -guest_kernel="${guest_kernels[0]}" - -# Setup dry-run staging if enabled -if $dry_run && $fix; then - setup_dryrun -fi - # Function to check if azure-vm-utils is installed check_azure_vm_utils() { echo "[INFO] Checking for azure-vm-utils..." @@ -191,11 +160,7 @@ check_azure_vm_utils() { echo "[WARNING] azure-vm-utils is not installed." echo "[WARNING] After conversion, /dev/disk/azure/ symlinks for NVMe disks may not be available." echo "[WARNING] Install azure-vm-utils from https://github.com/Azure/azure-vm-utils for best NVMe experience." - if $fix; then - _install_fallback_udev_rules - else - echo "[WARNING] Use --fix-os to install a fallback udev rule for basic NVMe symlinks and io_timeout." - fi + _install_fallback_udev_rules fi } @@ -231,12 +196,6 @@ _install_fallback_udev_rules() { return fi - if $dry_run; then - echo "[DRYRUN] Would install fallback udev rule at $_target" - echo "$_FALLBACK_UDEV_RULE" > "$staging_dir/modified/99-azure-nvme-fallback.rules" - return - fi - echo "[INFO] Installing fallback NVMe udev rule at $_target" echo "$_FALLBACK_UDEV_RULE" > "$_target" echo "[INFO] Offline guest: udev rules will load at the next boot." @@ -254,12 +213,6 @@ check_nvme_driver() { # Check if nvme is compiled directly into the kernel (built-in) if grep -qw nvme "/lib/modules/$(guest_kernel_version)/modules.builtin" 2>/dev/null; then echo "[INFO] NVMe driver is built into the kernel. No initramfs entry needed." - if $dry_run && $fix; then - echo "[DRYRUN] NVMe driver is built-in (kernel $(guest_kernel_version)). No initramfs or dracut changes needed." - echo "nvme_builtin=true" > "$staging_dir/modified/nvme-driver-status.txt" - echo "kernel=$(guest_kernel_version)" >> "$staging_dir/modified/nvme-driver-status.txt" - grep -w nvme "/lib/modules/$(guest_kernel_version)/modules.builtin" >> "$staging_dir/modified/nvme-driver-status.txt" - fi return 0 fi @@ -277,30 +230,16 @@ check_nvme_driver() { fi if $_initramfs_ok; then echo "[INFO] NVMe driver found in initrd/initramfs." - if $dry_run && $fix; then - echo "[DRYRUN] NVMe and pci-hyperv drivers already in initramfs. No changes needed." - echo "nvme_in_initramfs=true" > "$staging_dir/modified/nvme-driver-status.txt" - echo "kernel=$(guest_kernel_version)" >> "$staging_dir/modified/nvme-driver-status.txt" - fi else if modinfo -k "$guest_kernel" nvme &>/dev/null; then echo "[INFO] NVMe module exists on disk." fi - if $fix; then - if $dry_run; then - echo "[DRYRUN] Would run: update-initramfs -u -k all" - echo "update-initramfs -u -k all" > "$staging_dir/modified/initramfs-commands.txt" - else - echo "[INFO] Adding NVMe/pci-hyperv drivers to initrd/initramfs..." - update-initramfs -u -k all - if lsinitramfs /boot/initrd.img-* | grep -q nvme; then - echo "[INFO] NVMe driver added successfully." - else - echo "[ERROR] Failed to add NVMe driver to initrd/initramfs." - fi - fi + echo "[INFO] Adding NVMe/pci-hyperv drivers to initrd/initramfs..." + update-initramfs -u -k all + if lsinitramfs /boot/initrd.img-* | grep -q nvme; then + echo "[INFO] NVMe driver added successfully." else - echo "[ERROR] NVMe driver not found in initrd/initramfs." + echo "[ERROR] Failed to add NVMe driver to initrd/initramfs." fi fi ;; @@ -322,47 +261,32 @@ check_nvme_driver() { done if ! $_nvme_missing; then echo "[INFO] NVMe and pci-hyperv drivers found in initrd/initramfs." - if $dry_run && $fix; then - echo "[DRYRUN] NVMe and pci-hyperv drivers already in all initramfs images. No changes needed." - echo "nvme_in_initramfs=true" > "$staging_dir/modified/nvme-driver-status.txt" - echo "kernel=$(guest_kernel_version)" >> "$staging_dir/modified/nvme-driver-status.txt" - fi else if modinfo -k "$guest_kernel" nvme &>/dev/null; then echo "[INFO] NVMe module exists on disk but is not in all initramfs images." fi - if $fix; then - if $dry_run; then - echo "[DRYRUN] Would run: dracut -f --regenerate-all (with nvme nvme-core in /etc/dracut.conf.d/nvme.conf)" - echo 'add_drivers+=" nvme nvme-core pci-hyperv "' > "$staging_dir/modified/dracut-nvme.conf" - echo "dracut -f --regenerate-all" >> "$staging_dir/modified/initramfs-commands.txt" - else - echo "[INFO] Adding NVMe driver to initrd/initramfs (all kernels)..." - mkdir -p /etc/dracut.conf.d - echo 'add_drivers+=" nvme nvme-core pci-hyperv "' | tee /etc/dracut.conf.d/nvme.conf > /dev/null - dracut -f --regenerate-all - _verify_ok=true - for _img in /boot/initramfs-*.img; do - [ -f "$_img" ] || continue - [[ "$_img" == *kdump* ]] && continue - [[ "$_img" == *rescue* ]] && continue - if ! lsinitrd "$_img" 2>/dev/null | grep -q nvme; then - echo "[ERROR] NVMe driver still missing in $_img after rebuild." - _verify_ok=false - fi - if ! lsinitrd "$_img" 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then - echo "[ERROR] pci-hyperv/hv_pci driver still missing in $_img after rebuild." - _verify_ok=false - fi - done - if $_verify_ok; then - echo "[INFO] NVMe driver added successfully." - else - echo "[ERROR] Failed to add NVMe driver to all initramfs images." - fi + echo "[INFO] Adding NVMe driver to initrd/initramfs (all kernels)..." + mkdir -p /etc/dracut.conf.d + echo 'add_drivers+=" nvme nvme-core pci-hyperv "' | tee /etc/dracut.conf.d/nvme.conf > /dev/null + dracut -f --regenerate-all + _verify_ok=true + for _img in /boot/initramfs-*.img; do + [ -f "$_img" ] || continue + [[ "$_img" == *kdump* ]] && continue + [[ "$_img" == *rescue* ]] && continue + if ! lsinitrd "$_img" 2>/dev/null | grep -q nvme; then + echo "[ERROR] NVMe driver still missing in $_img after rebuild." + _verify_ok=false fi + if ! lsinitrd "$_img" 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then + echo "[ERROR] pci-hyperv/hv_pci driver still missing in $_img after rebuild." + _verify_ok=false + fi + done + if $_verify_ok; then + echo "[INFO] NVMe driver added successfully." else - echo "[ERROR] NVMe driver not found in initrd/initramfs." + echo "[ERROR] Failed to add NVMe driver to all initramfs images." fi fi ;; @@ -439,145 +363,83 @@ check_nvme_timeout() { if { [ -n "$_rhel7_efi_config" ] && nvme_timeout_entries_ready "$_rhel7_efi_config"; } || { [ -z "$_rhel7_efi_config" ] && grep -q "nvme_core.io_timeout=240" $_grub_check_files 2>/dev/null; }; then echo "[INFO] nvme_core.io_timeout is set to 240." - if $dry_run && $fix; then - echo "[DRYRUN] nvme_core.io_timeout already set to 240. No grub changes needed." - echo "nvme_core_io_timeout=240" > "$staging_dir/modified/nvme-timeout-status.txt" - echo "status=already_configured" >> "$staging_dir/modified/nvme-timeout-status.txt" - fi elif [ -z "$_rhel7_efi_config" ] && command -v grubby &>/dev/null && grubby --info=ALL 2>/dev/null | grep -q "nvme_core.io_timeout=240"; then echo "[INFO] nvme_core.io_timeout is set to 240 (BLS entries)." else echo "[WARNING] nvme_core.io_timeout is not set to 240." - if $fix; then - if $dry_run; then - echo "[DRYRUN] Staging grub changes..." - # Find the grub config file to stage - local grub_file="" + echo "[INFO] Setting nvme_core.io_timeout to 240..." + case "$distro" in + ubuntu) + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true update-grub + ;; + debian) + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true update-grub + ;; + suse|sles|opensuse*) if [ -f /etc/default/grub ]; then - grub_file="/etc/default/grub" + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + else + echo "[ERROR] /etc/default/grub not found." + return 1 fi - if [ -n "$grub_file" ]; then - cp "$grub_file" "$staging_dir/original/grub" - cp "$grub_file" "$staging_dir/modified/grub" - case "$distro" in - ubuntu) - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" - ;; - debian) - sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" - ;; - suse|sles|opensuse*) - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" - ;; - ol|azurelinux|mariner) - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" - ;; - *) - if [ -n "$_rhel7_efi_config" ]; then - set_rhel7_timeout_defaults "$staging_dir/modified/grub" || return 1 - echo "[DRYRUN] Would regenerate $_rhel7_efi_config" - else - sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' "$staging_dir/modified/grub" - fi - ;; - esac - diff -u "$staging_dir/original/grub" "$staging_dir/modified/grub" > "$staging_dir/diffs/grub.diff" 2>&1 || true - echo "[DRYRUN] Grub diff staged in $staging_dir/diffs/grub.diff" - cat "$staging_dir/diffs/grub.diff" - # Check for BLS (BootLoaderSpec) - RHEL 8+, AlmaLinux 8+, OL 8.10+ - if grep -q "GRUB_ENABLE_BLSCFG=true" "$grub_file" 2>/dev/null; then - echo "[INFO] BLS (BootLoaderSpec) is enabled." + ;; + redhat|rhel|centos|rocky|almalinux) + if [ -f /etc/default/grub ]; then + if [ -n "$_rhel7_efi_config" ]; then + set_rhel7_timeout_defaults /etc/default/grub || return 1 + if ! GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o "$_rhel7_efi_config"; then + echo "[ERROR] Failed to regenerate $_rhel7_efi_config." + return 1 + fi + else + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + fi + # Update BLS entries if applicable (RHEL 8+, AlmaLinux 8+) + if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then if command -v grubby &>/dev/null; then - echo "[DRYRUN] Would run: grubby --update-kernel=ALL --args=nvme_core.io_timeout=240" - echo "bls_enabled=true" >> "$staging_dir/modified/nvme-timeout-status.txt" - echo "grubby_available=true" >> "$staging_dir/modified/nvme-timeout-status.txt" - else - echo "[WARNING] BLS is enabled but grubby is not installed." - echo "bls_enabled=true" >> "$staging_dir/modified/nvme-timeout-status.txt" - echo "grubby_available=false" >> "$staging_dir/modified/nvme-timeout-status.txt" + grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" + echo "[INFO] Updated BLS entries via grubby." fi fi else - echo "[DRYRUN] No grub config found to stage." + echo "[ERROR] /etc/default/grub not found." + return 1 fi - else - echo "[INFO] Setting nvme_core.io_timeout to 240..." - case "$distro" in - ubuntu) - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true update-grub - ;; - debian) - sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true update-grub - ;; - suse|sles|opensuse*) - if [ -f /etc/default/grub ]; then - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg - else - echo "[ERROR] /etc/default/grub not found." - return 1 - fi - ;; - redhat|rhel|centos|rocky|almalinux) - if [ -f /etc/default/grub ]; then - if [ -n "$_rhel7_efi_config" ]; then - set_rhel7_timeout_defaults /etc/default/grub || return 1 - if ! GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o "$_rhel7_efi_config"; then - echo "[ERROR] Failed to regenerate $_rhel7_efi_config." - return 1 - fi - else - sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg - fi - # Update BLS entries if applicable (RHEL 8+, AlmaLinux 8+) - if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then - if command -v grubby &>/dev/null; then - grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" - echo "[INFO] Updated BLS entries via grubby." - fi - fi - else - echo "[ERROR] /etc/default/grub not found." - return 1 - fi - ;; - ol|azurelinux|mariner) - if [ -f /etc/default/grub ]; then - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg - # Update BLS entries if applicable (OL 8.10+) - if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then - if command -v grubby &>/dev/null; then - grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" - echo "[INFO] Updated BLS entries via grubby." - fi - fi - else - echo "[ERROR] /etc/default/grub not found." - return 1 + ;; + ol|azurelinux|mariner) + if [ -f /etc/default/grub ]; then + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + # Update BLS entries if applicable (OL 8.10+) + if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then + if command -v grubby &>/dev/null; then + grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" + echo "[INFO] Updated BLS entries via grubby." fi - ;; - *) - echo "[ERROR] Unsupported distribution for nvme_core.io_timeout fix." - return 1 - ;; - esac - - if { [ -n "$_rhel7_efi_config" ] && nvme_timeout_entries_ready "$_rhel7_efi_config"; } || - { [ -z "$_rhel7_efi_config" ] && grep -q "nvme_core.io_timeout=240" $_grub_check_files 2>/dev/null; }; then - echo "[INFO] nvme_core.io_timeout set successfully." - elif [ -z "$_rhel7_efi_config" ] && command -v grubby &>/dev/null && grubby --info=ALL 2>/dev/null | grep -q "nvme_core.io_timeout=240"; then - echo "[INFO] nvme_core.io_timeout set successfully (BLS entries)." + fi else - echo "[ERROR] Failed to set nvme_core.io_timeout." - if [ -n "$_rhel7_efi_config" ]; then return 1; fi + echo "[ERROR] /etc/default/grub not found." + return 1 fi - fi + ;; + *) + echo "[ERROR] Unsupported distribution for nvme_core.io_timeout fix." + return 1 + ;; + esac + + if { [ -n "$_rhel7_efi_config" ] && nvme_timeout_entries_ready "$_rhel7_efi_config"; } || + { [ -z "$_rhel7_efi_config" ] && grep -q "nvme_core.io_timeout=240" $_grub_check_files 2>/dev/null; }; then + echo "[INFO] nvme_core.io_timeout set successfully." + elif [ -z "$_rhel7_efi_config" ] && command -v grubby &>/dev/null && grubby --info=ALL 2>/dev/null | grep -q "nvme_core.io_timeout=240"; then + echo "[INFO] nvme_core.io_timeout set successfully (BLS entries)." else - echo "[ERROR] nvme_core.io_timeout is not set to 240." + echo "[ERROR] Failed to set nvme_core.io_timeout." + if [ -n "$_rhel7_efi_config" ]; then return 1; fi fi fi } @@ -589,96 +451,51 @@ check_fstab() { # because they use UUID-based addressing underneath. Only /dev/sd* and # /dev/disk/azure/scsi* paths break when disks move from SCSI to NVMe. if grep -Eq '/dev/sd[a-z][0-9]*|/dev/disk/azure/scsi[0-9]*/lun[0-9]*' /etc/fstab; then - if $fix; then - echo "[WARNING] /etc/fstab contains deprecated device names." - if $dry_run; then - echo "[DRYRUN] Staging fstab changes..." - cp /etc/fstab "$staging_dir/original/fstab" - - # Build modified fstab in staging directory - while read -r line; do - if [[ "$line" =~ ^[^#] ]]; then - device=$(echo "$line" | awk '{print $1}') - if [[ "$device" =~ ^/dev/sd[a-z][0-9]*$ ]]; then - uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') - if [ -n "$uuid" ]; then - newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") - echo "[DRYRUN] Would replace $device with UUID=$uuid" - echo "$newline" >> "$staging_dir/modified/fstab" - else - echo "[DRYRUN] Could not find UUID for $device. Would skip." - echo "$line" >> "$staging_dir/modified/fstab" - fi - elif [[ "$device" =~ ^/dev/disk/azure/scsi[0-9]*/lun[0-9]* ]]; then - uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') - if [ -n "$uuid" ]; then - newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") - echo "[DRYRUN] Would replace $device with UUID=$uuid" - echo "$newline" >> "$staging_dir/modified/fstab" - else - echo "[DRYRUN] Could not find UUID for $device. Would skip." - echo "$line" >> "$staging_dir/modified/fstab" - fi - else - echo "$line" >> "$staging_dir/modified/fstab" - fi + echo "[WARNING] /etc/fstab contains deprecated device names." + echo "[INFO] Replacing deprecated device names in /etc/fstab with UUIDs..." + + # Create a backup of the fstab file + cp /etc/fstab /etc/fstab.bak + + # Ensure fstab.new starts fresh (avoid stale leftovers from interrupted runs) + rm -f /etc/fstab.new + + # Use sed to replace device names with UUIDs + while read -r line; do + if [[ "$line" =~ ^[^#] ]]; then + device=$(echo "$line" | awk '{print $1}') + if [[ "$device" =~ ^/dev/sd[a-z][0-9]*$ ]]; then + uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') + if [ -n "$uuid" ]; then + newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") + echo "[INFO] Replaced $device with UUID=$uuid" + echo "$newline" >> /etc/fstab.new else - echo "$line" >> "$staging_dir/modified/fstab" + echo "[WARNING] Could not find UUID for $device. Skipping." + echo "$line" >> /etc/fstab.new fi - done < /etc/fstab - - diff -u "$staging_dir/original/fstab" "$staging_dir/modified/fstab" > "$staging_dir/diffs/fstab.diff" 2>&1 || true - echo "[DRYRUN] Fstab diff staged in $staging_dir/diffs/fstab.diff" - cat "$staging_dir/diffs/fstab.diff" - else - echo "[INFO] Replacing deprecated device names in /etc/fstab with UUIDs..." - - # Create a backup of the fstab file - cp /etc/fstab /etc/fstab.bak - - # Ensure fstab.new starts fresh (avoid stale leftovers from interrupted runs) - rm -f /etc/fstab.new - - # Use sed to replace device names with UUIDs - while read -r line; do - if [[ "$line" =~ ^[^#] ]]; then - device=$(echo "$line" | awk '{print $1}') - if [[ "$device" =~ ^/dev/sd[a-z][0-9]*$ ]]; then - uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') - if [ -n "$uuid" ]; then - newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") - echo "[INFO] Replaced $device with UUID=$uuid" - echo "$newline" >> /etc/fstab.new - else - echo "[WARNING] Could not find UUID for $device. Skipping." - echo "$line" >> /etc/fstab.new - fi - elif [[ "$device" =~ ^/dev/disk/azure/scsi[0-9]*/lun[0-9]* ]]; then - uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') - if [ -n "$uuid" ]; then - newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") - echo "[INFO] Replaced $device with UUID=$uuid" - echo "$newline" >> /etc/fstab.new - else - echo "[WARNING] Could not find UUID for $device. Skipping." - echo "$line" >> /etc/fstab.new - fi - else - echo "$line" >> /etc/fstab.new - fi + elif [[ "$device" =~ ^/dev/disk/azure/scsi[0-9]*/lun[0-9]* ]]; then + uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') + if [ -n "$uuid" ]; then + newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") + echo "[INFO] Replaced $device with UUID=$uuid" + echo "$newline" >> /etc/fstab.new else + echo "[WARNING] Could not find UUID for $device. Skipping." echo "$line" >> /etc/fstab.new fi - done < /etc/fstab + else + echo "$line" >> /etc/fstab.new + fi + else + echo "$line" >> /etc/fstab.new + fi + done < /etc/fstab - # Replace the old fstab with the new fstab - mv /etc/fstab.new /etc/fstab + # Replace the old fstab with the new fstab + mv /etc/fstab.new /etc/fstab - echo "[INFO] /etc/fstab updated with UUIDs. Original fstab backed up to /etc/fstab.bak" - fi - else - echo "[ERROR] /etc/fstab contains device names causing issues switching to NVMe" - fi + echo "[INFO] /etc/fstab updated with UUIDs. Original fstab backed up to /etc/fstab.bak" else echo "[INFO] /etc/fstab does not contain deprecated device names." fi @@ -692,20 +509,4 @@ done check_nvme_timeout check_fstab -# Generate dry-run summary report -if $dry_run && $fix; then - echo "" - echo "[DRYRUN] ============================================" - echo "[DRYRUN] Summary report for $(hostname)" - echo "[DRYRUN] Distro: $distro | Kernel: $(guest_kernel_version)" - echo "[DRYRUN] Staging directory: $staging_dir" - echo "[DRYRUN] ============================================" - echo "[DRYRUN] Files in staging directory:" - find "$staging_dir" -type f | sort | while read -r f; do - echo "[DRYRUN] $f" - done - echo "[DRYRUN] ============================================" - echo "[DRYRUN] No system files were modified." -fi - exit 0 diff --git a/tests/nvme/README.md b/tests/nvme/README.md index 622bb05..3a174b0 100644 --- a/tests/nvme/README.md +++ b/tests/nvme/README.md @@ -25,25 +25,29 @@ From the repository root: sudo python3 -B -m unittest discover -s tests/nvme -p 'test_*.py' -v ``` -The 25 tests need only this ALAR checkout, not a sibling CLI repository: +The 27 tests need only this ALAR checkout, not a sibling CLI repository: | File | Coverage | | --- | --- | -| [test_offline.py](test_offline.py) | Seven guest-kernel, multi-kernel, explicit swap mapping, ambiguous device, invalid/missing map and missing-kernel regressions. | -| [test_efi_timeout.py](test_efi_timeout.py) | Thirteen RHEL 7 standalone EFI regressions: stale configurations, exact/all-kernel timeout tokens, nonmutation, idempotence, broken links, redirect stubs, BIOS/modern releases and failed/ineffective generation. | -| [test_runner.py](test_runner.py) | Five harness regressions: raw success/failure evidence, equally broken scripts, unexpected success and copied shebang interpreters. | +| [test_offline.py](test_offline.py) | Nine guest-kernel/device regressions, including identical default/explicit fix behavior and rejection of removed modes before any changes. | +| [test_efi_timeout.py](test_efi_timeout.py) | Twelve RHEL 7 standalone EFI regressions: stale configurations, exact/all-kernel timeout tokens, idempotence, broken links, redirect stubs, BIOS/modern releases and failed/ineffective generation. | +| [test_runner.py](test_runner.py) | Six harness regressions: raw success/failure evidence, equally broken scripts, unexpected success, copied interpreters and the fix-only matrix. | EFI cases extract the actual action function bodies instead of maintaining a second copy of the timeout algorithm. ## Optional shared-source comparison -[run_tests.py](run_tests.py) compares 191 isolated scenarios across 12 distro IDs, -driver states, check/fix/dry-run modes, legacy release files, GRUB/BLS/udev -variants, image exclusions and missing/failing tools. It first compares shared -function bodies and fallback rules, allowing only the declared offline adapters: -installed guest kernels, explicit guest-device resolution, deferred udev reload, -and ALAR's fix default/check-only flag. +[run_tests.py](run_tests.py) compares 65 isolated fix/error scenarios across 12 +distro IDs, driver states, legacy release files, GRUB/BLS/udev variants, image +exclusions and missing/failing tools. These retain all fix/error cases from the +earlier 191-case matrix; check/dry-run cases no longer apply. + +The runner verifies unchanged timeout helper bodies, fallback rules and required +repair entrypoints. Repair function bodies intentionally omit non-fix branches; +their behavior is compared through the fixtures, not claimed to be text-identical. +Offline adaptations remain installed guest kernels, explicit guest-device +resolution and deferred udev reload. Supply the Azure CLI extension source explicitly. It is parsed with Python's AST, never imported. The reference used for this implementation includes the @@ -64,10 +68,12 @@ sudo python3 -B tests/nvme/run_tests.py \ Reports/evidence must be new paths outside the checkout. Workers are independent, default to at most four, and each shell phase has a 60-second timeout. The runner rejects unexpected exits, including equally broken scripts, and asserts that -check/dry-run leave protected guest files unchanged. +invalid inputs do not change protected guest files. -The JSON report records completion status, actual counts, source hashes and -per-case results. Optional evidence retains both scripts, raw stdout/stderr, +The schema-version-2 JSON report records completion status, actual counts, source +hashes, timeout-helper/rule checks and per-case results. It no longer claims that +all original function bodies match. Optional schema-version-1 case evidence +retains both scripts, raw stdout/stderr, exits, command transcripts, before/after contents and modes, and distro summaries. Only comparison output is normalized; raw evidence is preserved. An incomplete report, a printed error with exit zero, or a passing fixture is not successful @@ -88,7 +94,11 @@ The action is embedded and materialized through the existing built-in script mechanism; there are no new Rust dependencies or changes to action execution, disk discovery or ADE handling. -## Completed live coverage and boundaries +## Earlier live coverage and boundaries + +These live results belong to the earlier multi-mode candidates. The fix-only +revision is validated by local repair regressions and fix-mode differential +fixtures, not a new live VM campaign. - The x64 campaign exercised the action, actual SCSI/NVMe boots, repeat behavior and timeout faults. RHEL 7.9's standalone EFI correction passed real NVMe boot diff --git a/tests/nvme/run_tests.py b/tests/nvme/run_tests.py index bdc6fb9..8bc43f4 100644 --- a/tests/nvme/run_tests.py +++ b/tests/nvme/run_tests.py @@ -1,4 +1,4 @@ -"""Compare Linux NVMe preparation logic in parallel, isolated chroot fixtures. +"""Compare fix-only Linux NVMe preparation in parallel, isolated chroot fixtures. Requires Linux root, Python 3.10+ and existing userspace tools. The extension's literal _LINUX_SCRIPT is read with AST, never imported. Reference and candidate @@ -220,13 +220,12 @@ def fixture(base: Path, root: Path, case: Case, script: str, original: bool) -> def normalized(text: str) -> str: - """Remove only declared offline diagnostics, diff timestamps and check-flag usage. + """Remove only declared offline diagnostics and unsupported reference usage flags. Use this for comparisons, never for the retained raw stdout/stderr evidence. """ text = re.sub(r'^\[INFO\] Offline guest:.*\n|^\[WARNING\] Cannot map guest device .*\n', '', text, flags=re.MULTILINE) - text = re.sub(r'^(--- |\+\+\+ )([^\t\n]+)\t[^\n]*', r'\1\2', text, flags=re.MULTILINE) - return text.replace('[-check] ', '') + return text.replace('[-check] ', '').replace(' [-dryrun]', '') def snapshot(root: Path, normalize_content: bool = True) -> dict[str, tuple[int, str]]: @@ -247,7 +246,7 @@ def compare(base: Path, parent: Path, case: Case, reference: str, action: str, Each chroot phase has a 60-second timeout and an independently expected exit, so equally broken scripts cannot pass by equality alone. Compare normalized - output, guest files, BLS arguments, mapping behavior and check/dry-run nonmutation. + output, guest files, BLS arguments, mapping behavior and invalid-input nonmutation. When evidence_directory is supplied, write a new schema-version-1 trace with raw streams, commands and literal snapshots, including caught partial failures. Existing evidence files are rejected rather than overwritten. @@ -263,8 +262,7 @@ def compare(base: Path, parent: Path, case: Case, reference: str, action: str, fixture(base, root, case, script, original=index == 0) before = {name: value for name, value in snapshot(root).items() if not name.startswith('tmp/')} args = {'fix': ['-fix'] if index == 0 else [], - 'check': [] if index == 0 else ['-check'], - 'dryrun': ['-dryrun'], 'invalid': ['-invalid']}[case.mode] + 'invalid': ['-invalid']}[case.mode] command = ['/usr/sbin/chroot', str(root), '/bin/bash', '/run.sh', *args] phase: dict[str, object] = {'script': 'original' if index == 0 else 'candidate', 'command': command, 'before': snapshot(root, False)} @@ -279,14 +277,14 @@ def compare(base: Path, parent: Path, case: Case, reference: str, action: str, raise AssertionError(f'Unexpected script exit {result.returncode}; expected {expected_exit}: ' f'{result.stdout}{result.stderr}') outputs.append((result.returncode, normalized(result.stdout + result.stderr))) - if case.mode in ('check', 'dryrun'): + if case.mode == 'invalid' or case.scenario == 'no-release': after = {name: value for name, value in snapshot(root).items() if not name.startswith('tmp/')} if before != after: - raise AssertionError(f'{case.mode} modified protected guest files') + raise AssertionError('Invalid input modified protected guest files') if outputs[0] != outputs[1]: raise AssertionError(f'Original output: {outputs[0]}\nCandidate output: {outputs[1]}') if snapshot(roots[0]) != snapshot(roots[1]): - raise AssertionError('Guest configuration, image or dry-run artifacts differ') + raise AssertionError('Guest configuration or image contents differ') if (roots[0] / 'bls-args').read_bytes() != (roots[1] / 'bls-args').read_bytes(): raise AssertionError('BLS arguments differ') log = (roots[1] / 'commands.log').read_text() @@ -311,30 +309,29 @@ def compare(base: Path, parent: Path, case: Case, reference: str, action: str, def matrix() -> list[Case]: - """Return the 191 distro/driver/mode/fallback/error regression cases.""" - cases = [Case(distro, state, mode) for distro in DISTROS - for state in ('missing', 'ready', 'builtin') for mode in ('fix', 'check', 'dryrun')] - cases += [Case(distro, state, mode) for distro in ('ubuntu', 'rhel') - for state in ('no-hvpci', 'no-nvme') for mode in ('fix', 'check', 'dryrun')] + """Return 65 fix-mode, release-detection, fallback and error cases.""" + cases = [Case(distro, state, 'fix') for distro in DISTROS + for state in ('missing', 'ready', 'builtin')] + cases += [Case(distro, state, 'fix') for distro in ('ubuntu', 'rhel') + for state in ('no-hvpci', 'no-nvme')] scenarios = ('no-grubby', 'bls-ready', 'defaults-ready', 'grub2-ready', 'grub-ready', 'utils-missing-rules', 'utils-etc', 'utils-lib', 'utils-usrlib', 'fallback-ready', 'no-grub-file', 'failed-rebuild', 'fail-dracut', 'fail-grub', 'no-fstab-changes') - cases += [Case('rhel', 'missing', mode, scenario) for scenario in scenarios for mode in ('fix', 'check', 'dryrun')] - cases += [Case('ubuntu', 'missing', mode, scenario) for scenario in ('failed-rebuild', 'fail-update') for mode in ('fix', 'check', 'dryrun')] - cases += [Case('ignored', 'missing', mode, f'legacy-{release}') - for release in ('debian_version', 'SuSE-release', 'redhat-release', 'centos-release', 'rocky-release') - for mode in ('fix', 'check', 'dryrun')] - cases += [Case('arch', 'missing', mode) for mode in ('fix', 'check', 'dryrun')] + cases += [Case('rhel', 'missing', 'fix', scenario) for scenario in scenarios] + cases += [Case('ubuntu', 'missing', 'fix', scenario) for scenario in ('failed-rebuild', 'fail-update')] + cases += [Case('ignored', 'missing', 'fix', f'legacy-{release}') + for release in ('debian_version', 'SuSE-release', 'redhat-release', 'centos-release', 'rocky-release')] + cases += [Case('arch', 'missing', 'fix')] return cases + [Case('ignored', 'missing', 'fix', 'no-release'), Case('ubuntu', 'missing', 'invalid')] def verify_functions(reference: str, action: str) -> None: - """Reject changes beyond declared offline adapters in original shell functions. + """Verify unchanged timeout helpers/rules and required repair entrypoints. - Compare original and shared timeout helper function bodies and the complete fallback udev rule literally, - allowing only the named guest-kernel/device/udev/usage adaptations. + Repair functions have intentionally lost their non-fix branches; compare + their behavior through fixtures, not a claim of literal source identity. """ - for name in ('setup_dryrun', 'usage', 'check_azure_vm_utils', '_install_fallback_udev_rules', + for name in ('check_azure_vm_utils', '_install_fallback_udev_rules', 'check_nvme_driver', 'nvme_timeout_entries_ready', 'set_rhel7_timeout_defaults', 'check_nvme_timeout', 'check_fstab'): bodies = [] @@ -344,12 +341,8 @@ def verify_functions(reference: str, action: str) -> None: raise ValueError(f'Missing original function: {name}') bodies.append('\n'.join(line for line in match[0].splitlines() if not line.lstrip().startswith('#') and 'echo "Usage:' not in line)) - expected = bodies[0].replace('uname -r', 'guest_kernel_version').replace('modinfo nvme', 'modinfo -k "$guest_kernel" nvme') - expected = expected.replace('blkid "$device"', 'guest_blkid "$device"').replace( - 'udevadm control --reload-rules 2>/dev/null || true', - 'echo "[INFO] Offline guest: udev rules will load at the next boot."') - if expected != bodies[1]: - raise ValueError(f'Original function differs beyond offline adapters: {name}') + if name in ('nvme_timeout_entries_ready', 'set_rhel7_timeout_defaults') and bodies[0] != bodies[1]: + raise ValueError(f'Shared timeout helper differs: {name}') rules = [re.search(r"^_FALLBACK_UDEV_RULE=.*?^LABEL=.*?'$", text, re.MULTILINE | re.DOTALL) for text in (reference, action)] if any(rule is None for rule in rules) or [rule[0] for rule in rules if rule is not None][0] != [rule[0] for rule in rules if rule is not None][1]: raise ValueError('Fallback udev rules differ') @@ -389,7 +382,7 @@ def main() -> int: verify_functions(reference, action) report.parent.mkdir(parents=True, exist_ok=True) with report.open('x', encoding='utf-8') as stream: - json.dump({'schema_version': 1, 'status': 'incomplete', 'mode': 'offline-fixtures'}, stream) + json.dump({'schema_version': 2, 'status': 'incomplete', 'mode': 'offline-fix-fixtures'}, stream) if evidence is not None: evidence.mkdir(parents=True, exist_ok=False) (evidence / 'original-linux-script.sh').write_text(reference, encoding='utf-8') @@ -406,9 +399,10 @@ def main() -> int: if result['status'] == 'failed': print(f"FAIL {result['case']}: {result['error']}", file=sys.stderr) failed = sum(result['status'] == 'failed' for result in results) - document = {'schema_version': 1, 'status': 'completed', 'mode': 'offline-fixtures', 'completed_at': datetime.now(timezone.utc).isoformat(), + document = {'schema_version': 2, 'status': 'completed', 'mode': 'offline-fix-fixtures', 'completed_at': datetime.now(timezone.utc).isoformat(), 'workers': args.jobs, 'total': len(results), 'passed': len(results) - failed, 'failed': failed, - 'original_functions_match': True, 'action_sha256': hashlib.sha256(action.encode()).hexdigest(), + 'timeout_helpers_match': True, 'fallback_rules_match': True, + 'action_sha256': hashlib.sha256(action.encode()).hexdigest(), 'reference_sha256': hashlib.sha256(reference.encode()).hexdigest(), 'results': sorted(results, key=lambda row: row['case']), 'evidence_directory': str(evidence) if evidence is not None else None, 'execution_host': {'wsl_distribution': os.environ.get('WSL_DISTRO_NAME'), 'python': sys.version, diff --git a/tests/nvme/test_efi_timeout.py b/tests/nvme/test_efi_timeout.py index 44a1c1a..430f240 100644 --- a/tests/nvme/test_efi_timeout.py +++ b/tests/nvme/test_efi_timeout.py @@ -27,7 +27,7 @@ def setUpClass(cls): repo = Path(__file__).resolve().parents[2] cls.scripts = ((repo / 'src/action_implementation/nvme-impl.sh').read_text(),) - def run_case(self, script, mode='fix', version='7.9', efi=True, ready=False, + def run_case(self, script, version='7.9', efi=True, ready=False, token='', broken=False, redirect=False, failure=False, missing_defaults=False, silent_failure=False, other_kernel_missing=False): """Run actual function definitions against synthetic boot entries and logged rebuilds.""" temporary = tempfile.TemporaryDirectory(dir=self.tmp.name) @@ -51,12 +51,8 @@ def run_case(self, script, mode='fix', version='7.9', efi=True, ready=False, (root / 'bin/grub2-mkconfig').chmod(0o755) write(root, 'commands.log', '') write(root, 'dev/null', '') - for directory in ('tmp/staging/original', 'tmp/staging/modified', 'tmp/staging/diffs'): - (root / directory).mkdir(parents=True, exist_ok=True) functions = '\n\n'.join(re.findall(r'^(?:nvme_timeout_entries_ready|set_rhel7_timeout_defaults|check_nvme_timeout)\(\) \{\n.*?^\}', script, re.MULTILINE | re.DOTALL)) - write(root, 'run.sh', functions + '\ndistro=rhel\nfix=' + ('false' if mode == 'check' else 'true') - + '\ndry_run=' + ('true' if mode == 'dryrun' else 'false') - + '\nstaging_dir=/tmp/staging\ncheck_nvme_timeout\n') + write(root, 'run.sh', functions + '\ndistro=rhel\ncheck_nvme_timeout\n') before = {str(path.relative_to(root)): path.read_bytes() for path in (root / 'boot').rglob('*') if path.is_file()} result = subprocess.run(['/usr/sbin/chroot', str(root), '/bin/bash', '/run.sh'], env={'PATH': '/bin'}, text=True, capture_output=True, timeout=30) @@ -68,9 +64,11 @@ def each_source(self, **kwargs): def test_stale_efi_is_not_ready_from_defaults_or_other_config(self): """The exact live failure must not report readiness from the wrong files.""" - for root, result, _ in self.each_source(mode='check'): - self.assertIn('[ERROR] nvme_core.io_timeout is not set to 240.', result.stdout) + for root, result, _ in self.each_source(): + self.assertEqual(result.returncode, 0) + self.assertIn('[WARNING] nvme_core.io_timeout is not set to 240.', result.stdout) self.assertNotIn('[INFO] nvme_core.io_timeout is set to 240.', result.stdout) + self.assertIn('grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg', (root/'commands.log').read_text()) def test_fix_rebuilds_standalone_efi_without_duplicate_default_argument(self): """Repair the proven standalone EFI target even when desired defaults already have 240.""" @@ -90,16 +88,11 @@ def test_ready_standalone_efi_is_idempotent(self): def test_partial_or_wrong_argument_is_not_ready(self): """2400 and a conflicting timeout must not be accepted as 240.""" for token in ('nvme_core.io_timeout=2400', 'nvme_core.io_timeout=240 nvme_core.io_timeout=30'): - for root, result, _ in self.each_source(mode='check', token=token): - self.assertIn('[ERROR] nvme_core.io_timeout is not set to 240.', result.stdout) - - def test_dryrun_does_not_change_boot_files(self): - """Stage defaults and target diagnostics without rebuilding real fixture files.""" - for root, result, before in self.each_source(mode='dryrun'): - after = {str(path.relative_to(root)): path.read_bytes() for path in (root/'boot').rglob('*') if path.is_file()} - self.assertEqual(before, after) - self.assertIn('/boot/efi/EFI/redhat/grub.cfg', result.stdout) - self.assertNotIn('grub2-mkconfig', (root/'commands.log').read_text()) + for root, result, _ in self.each_source(token=token): + self.assertEqual(result.returncode, 0) + self.assertIn('[WARNING] nvme_core.io_timeout is not set to 240.', result.stdout) + self.assertEqual((root/'boot/efi/EFI/redhat/grub.cfg').read_text().count('nvme_core.io_timeout='), 1) + self.assertIn('nvme_core.io_timeout=240 ', (root/'boot/efi/EFI/redhat/grub.cfg').read_text()) def test_broken_efi_target_is_explicit_error(self): """A broken configured EFI link must not fall through to false readiness.""" @@ -142,8 +135,10 @@ def test_missing_defaults_is_error(self): def test_every_standalone_kernel_entry_requires_timeout(self): """One ready entry cannot mask an older kernel without the required flag.""" - for root, result, _ in self.each_source(mode='check', token='nvme_core.io_timeout=240', other_kernel_missing=True): - self.assertIn('[ERROR] nvme_core.io_timeout is not set to 240.', result.stdout) + for root, result, _ in self.each_source(token='nvme_core.io_timeout=240', other_kernel_missing=True): + self.assertEqual(result.returncode, 0) + self.assertIn('[WARNING] nvme_core.io_timeout is not set to 240.', result.stdout) + self.assertIn('grub2-mkconfig', (root/'commands.log').read_text()) def test_successful_generator_without_repair_is_rejected(self): """An exit-zero generator that leaves stale EFI entries is not a successful fix.""" diff --git a/tests/nvme/test_offline.py b/tests/nvme/test_offline.py index 5eae258..baa4f0c 100644 --- a/tests/nvme/test_offline.py +++ b/tests/nvme/test_offline.py @@ -1,4 +1,4 @@ -"""Seven regressions for ALAR's offline guest-kernel and device-map adapters. +"""Regressions for ALAR's fix-only interface and offline guest adapters. Run through unittest discovery as Linux root with the same copied-tool/chroot prerequisites as run_tests.py. Other hosts skip this class, not certify it. @@ -15,7 +15,7 @@ import tempfile import unittest -from run_tests import Case, fixture, prepare_base, write +from run_tests import Case, fixture, prepare_base, snapshot, write @unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required for isolated chroot fixtures') @@ -111,6 +111,37 @@ def test_missing_guest_kernels_prevent_mutations(self): self.assertIn('[ERROR] No installed guest kernels', result.stdout) self.assertEqual(self.log(), '') + def test_explicit_fix_matches_default(self): + """The optional fix flag and normal ALAR invocation must make identical repairs.""" + self.prepare() + explicit = Path(self.directory.name) / 'explicit' + shutil.copytree(self.root, explicit) + default_result = self.run_action() + explicit_result = subprocess.run( + ['/usr/sbin/chroot', str(explicit), '/bin/bash', '/run.sh', '-fix'], + env={'PATH': '/bin', 'ALAR_NVME_DEVICE_MAP': '/device-map'}, + capture_output=True, text=True, timeout=60) + self.assertEqual(default_result.returncode, 0) + self.assertEqual(explicit_result.returncode, 0) + self.assertEqual(default_result.stdout, explicit_result.stdout) + self.assertEqual(default_result.stderr, explicit_result.stderr) + self.assertEqual(snapshot(self.root, False), snapshot(explicit, False)) + self.assertIn('UUID=swap-uuid none swap', (explicit / 'etc/fstab').read_text()) + + def test_removed_modes_fail_before_any_changes(self): + """Removed flags must fail explicitly, never fall through into a repair.""" + self.prepare() + before = snapshot(self.root, False) + for arguments in (['-check'], ['-dryrun'], ['-check', '-fix'], ['-fix', '-dryrun']): + with self.subTest(arguments=arguments): + result = subprocess.run( + ['/usr/sbin/chroot', str(self.root), '/bin/bash', '/run.sh', *arguments], + env={'PATH': '/bin'}, capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 1) + self.assertIn('Usage: /run.sh [-fix]', result.stdout) + self.assertEqual(before, snapshot(self.root, False)) + self.assertEqual(self.log(), '') + if __name__ == '__main__': unittest.main() diff --git a/tests/nvme/test_runner.py b/tests/nvme/test_runner.py index e7c6991..e551bb2 100644 --- a/tests/nvme/test_runner.py +++ b/tests/nvme/test_runner.py @@ -1,4 +1,4 @@ -"""Five regressions for fixture validity, raw evidence and interpreter copying. +"""Regressions for fix-only fixtures, raw evidence and interpreter copying. Run with unittest discovery as Linux root and existing chroot/userspace tools. Other hosts skip this class; that is not guest acceptance. Tests reject equally @@ -16,7 +16,7 @@ import tempfile import unittest -from run_tests import Case, compare, copy_tool, prepare_base, write +from run_tests import Case, compare, copy_tool, matrix, prepare_base, write @unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required for isolated fixtures') @@ -28,9 +28,9 @@ def test_raw_case_evidence_keeps_streams_and_file_snapshots(self): parent = Path(directory) prepare_base(parent / 'base') script = 'echo standard-output; echo standard-error >&2\n' - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'check'), script, script, parent / 'review') + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'fix', 'no-fstab-changes'), script, script, parent / 'review') self.assertEqual(result['status'], 'passed') - evidence = json.loads((parent / 'review/ubuntu/ready/check/normal.json').read_text()) + evidence = json.loads((parent / 'review/ubuntu/ready/fix/no-fstab-changes.json').read_text()) self.assertFalse(evidence['boot_evidence']) self.assertEqual(len(evidence['phases']), 2) for phase in evidence['phases']: @@ -45,9 +45,9 @@ def test_failed_case_preserves_actual_exit_in_evidence(self): with tempfile.TemporaryDirectory(prefix='alar-failed-evidence-') as directory: parent = Path(directory) prepare_base(parent / 'base') - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'check'), 'if then\n', 'if then\n', parent / 'review') + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'fix'), 'if then\n', 'if then\n', parent / 'review') self.assertEqual(result['status'], 'failed') - evidence = json.loads((parent / 'review/ubuntu/ready/check/normal.json').read_text()) + evidence = json.loads((parent / 'review/ubuntu/ready/fix/normal.json').read_text()) self.assertEqual(evidence['phases'][0]['returncode'], 2) self.assertEqual(evidence['result']['status'], 'failed') @@ -56,7 +56,7 @@ def test_equal_shell_errors_are_failures(self): with tempfile.TemporaryDirectory(prefix='alar-equal-errors-') as directory: parent = Path(directory) prepare_base(parent / 'base') - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'check'), 'if then\n', 'if then\n') + result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'fix'), 'if then\n', 'if then\n') self.assertEqual(result['status'], 'failed') self.assertIn('Unexpected script exit 2', result['error']) @@ -86,6 +86,13 @@ def test_shebang_fixture_copies_interpreter(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout, 'copied-interpreter') + def test_matrix_only_contains_fix_and_invalid_input(self): + """Retain every fix scenario without advertising removed modes.""" + cases = matrix() + self.assertEqual(len(cases), 65) + self.assertEqual(len({case.name for case in cases}), 65) + self.assertEqual({case.mode for case in cases}, {'fix', 'invalid'}) + if __name__ == '__main__': unittest.main() From f7b22a4cfc50b429c0aa54cc636aa76e9b104e2c Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Tue, 24 Nov 2026 21:04:20 -0600 Subject: [PATCH 3/9] Keep NVMe contribution scoped to the action Preserve the developer test harness separately and remove it from the contribution. Keep only the action, minimal built-in wiring and usage documentation, including the unchanged Oracle framework limitation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 15 +- tests/nvme/README.md | 124 ---------- tests/nvme/run_tests.py | 425 --------------------------------- tests/nvme/test_efi_timeout.py | 147 ------------ tests/nvme/test_offline.py | 147 ------------ tests/nvme/test_runner.py | 98 -------- 6 files changed, 5 insertions(+), 951 deletions(-) delete mode 100644 tests/nvme/README.md delete mode 100644 tests/nvme/run_tests.py delete mode 100644 tests/nvme/test_efi_timeout.py delete mode 100644 tests/nvme/test_offline.py delete mode 100644 tests/nvme/test_runner.py diff --git a/README.md b/README.md index 88ed797..b3de0ec 100644 --- a/README.md +++ b/README.md @@ -92,16 +92,11 @@ running the script without arguments. Check-only and dry-run modes are not supported; no additional flags are added to ALAR's CLI. **Known framework limitation:** some Oracle Linux disk layouts are classified as -ADE-encrypted before ALAR reaches the action. Oracle Linux 8.10, 9.8 and 9.7 passed -full action/conversion testing with a separate temporary framework patch, but -that patch was reverted and is not included here. Those results do not mean the -unchanged framework can process those layouts. Genuine ADE credential recovery -and reliable post-conversion SSH connectivity are not certified by these tests. - -The original fix-path diagnostic and exit behavior is preserved: review the action output, -not just ALAR's exit status, when evaluating preparation results. -The [NVMe test guide](tests/nvme/README.md) documents the self-contained regression -suite, optional shared-source comparisons, completed live coverage and limits. +ADE-encrypted before ALAR reaches the action. This action does not change disk +discovery or ADE handling and cannot bypass that limitation. + +The original fix-path diagnostic and exit behavior is preserved: review the +action output, not just ALAR's exit status, when evaluating preparation results. #### grubfix This action is reinstalling `GRUB` and regenerates the `grub.cfg` file diff --git a/tests/nvme/README.md b/tests/nvme/README.md deleted file mode 100644 index 3a174b0..0000000 --- a/tests/nvme/README.md +++ /dev/null @@ -1,124 +0,0 @@ -# Linux NVMe action tests - -These are offline regression tests for the built-in `nvme` action. They do not -deploy VMs, contact Azure or SSH, mount filesystems, install packages, or add -runtime health checks. Session ledgers, live deployment helpers, quota tooling -and raw cloud evidence are not part of this suite. - -## Requirements - -- Linux root, including root inside WSL, and Python 3.10+. -- Existing `/usr/sbin/chroot`, `ldd`, Bash, coreutils, grep, sed, awk, diff and - find. The runner copies the required tools and their interpreters/libraries - into disposable chroots; missing prerequisites fail the run. -- Each guest uses fake files and stubbed device/repair commands. Tests never - access real guest disks or use the rescue host's device identities. - -Non-Linux or non-root hosts skip the chroot test classes. A skipped suite is not -successful execution or live NVMe acceptance. - -## Self-contained regression suite - -From the repository root: - -```bash -sudo python3 -B -m unittest discover -s tests/nvme -p 'test_*.py' -v -``` - -The 27 tests need only this ALAR checkout, not a sibling CLI repository: - -| File | Coverage | -| --- | --- | -| [test_offline.py](test_offline.py) | Nine guest-kernel/device regressions, including identical default/explicit fix behavior and rejection of removed modes before any changes. | -| [test_efi_timeout.py](test_efi_timeout.py) | Twelve RHEL 7 standalone EFI regressions: stale configurations, exact/all-kernel timeout tokens, idempotence, broken links, redirect stubs, BIOS/modern releases and failed/ineffective generation. | -| [test_runner.py](test_runner.py) | Six harness regressions: raw success/failure evidence, equally broken scripts, unexpected success, copied interpreters and the fix-only matrix. | - -EFI cases extract the actual action function bodies instead of maintaining a -second copy of the timeout algorithm. - -## Optional shared-source comparison - -[run_tests.py](run_tests.py) compares 65 isolated fix/error scenarios across 12 -distro IDs, driver states, legacy release files, GRUB/BLS/udev variants, image -exclusions and missing/failing tools. These retain all fix/error cases from the -earlier 191-case matrix; check/dry-run cases no longer apply. - -The runner verifies unchanged timeout helper bodies, fallback rules and required -repair entrypoints. Repair function bodies intentionally omit non-fix branches; -their behavior is compared through the fixtures, not claimed to be text-identical. -Offline adaptations remain installed guest kernels, explicit guest-device -resolution and deferred udev reload. - -Supply the Azure CLI extension source explicitly. It is parsed with Python's -AST, never imported. The reference used for this implementation includes the -RHEL 7 EFI correction: -[`_linux_script.py` at commit `2ac43a5b`](https://github.com/jonathanbrenes/azure-cli-extensions/blob/2ac43a5b1f338177a2da1c114cae6c674d03caec/src/nvme-conversion/azext_nvme_conversion/_linux_script.py). -An older or changed reference that fails function comparison is not equivalent -coverage and must not be silently substituted. - -```bash -stamp=$(date +%Y%m%d-%H%M%S)-$$ -sudo python3 -B tests/nvme/run_tests.py \ - --reference /path/to/azure-cli-extensions/src/nvme-conversion/azext_nvme_conversion/_linux_script.py \ - --report "/tmp/alar-nvme-${stamp}.json" \ - --evidence-dir "/tmp/alar-nvme-${stamp}-evidence" \ - --jobs 4 -``` - -Reports/evidence must be new paths outside the checkout. Workers are independent, -default to at most four, and each shell phase has a 60-second timeout. The runner -rejects unexpected exits, including equally broken scripts, and asserts that -invalid inputs do not change protected guest files. - -The schema-version-2 JSON report records completion status, actual counts, source -hashes, timeout-helper/rule checks and per-case results. It no longer claims that -all original function bodies match. Optional schema-version-1 case evidence -retains both scripts, raw stdout/stderr, -exits, command transcripts, before/after contents and modes, and distro summaries. -Only comparison output is normalized; raw evidence is preserved. An incomplete -report, a printed error with exit zero, or a passing fixture is not successful -NVMe boot certification. Exit 0 means all comparisons passed; 1 means completed -comparisons failed; argument errors return 2. Setup failures also fail the run. - -## Build checks - -Use the repository's existing Rust toolchain/dependencies: - -```bash -bash -n src/action_implementation/nvme-impl.sh -cargo test --locked -cargo build --release --locked -``` - -The action is embedded and materialized through the existing built-in script -mechanism; there are no new Rust dependencies or changes to action execution, -disk discovery or ADE handling. - -## Earlier live coverage and boundaries - -These live results belong to the earlier multi-mode candidates. The fix-only -revision is validated by local repair regressions and fix-mode differential -fixtures, not a new live VM campaign. - -- The x64 campaign exercised the action, actual SCSI/NVMe boots, repeat behavior - and timeout faults. RHEL 7.9's standalone EFI correction passed real NVMe boot - and effective-timeout-240 checks after the original false-readiness failure. -- Native ARM64 GNU and static musl builds succeeded. The static candidate passed - full action phases, actual boots, runtime timeout checks, repeat and fault tests - on Ubuntu 26.04, Debian 13 and Oracle Linux 10.2 ARM64. -- Oracle Linux 8.10, 9.8 and 9.7 x64 passed full action phases, 12 actual boots, - six runtime-timeout-240 assertions, repeat and fault checks **only with a - separate temporary framework candidate**. Its patch was reverted. The - unchanged framework can still misclassify those plaintext layouts as ADE - before reaching this action; no framework fix is included in this change. -- Genuine ADE recovery with valid, missing or wrong credentials was not - live-tested. Existing ADE code was not changed. -- Reliable post-conversion SSH remains unverified. Run Command and actual boot - evidence do not certify SSH connectivity. -- Legacy SCSI-only image component tests are not NVMe conversion certification. - Windows and universal image/SKU compatibility are out of scope. - -Live results describe the tested candidates, not an automatic test run by this -suite. Full logs, candidate/source hashes and per-image evidence are retained -separately; no local machine paths, credentials or cloud resource inventories -are required to run the checked-in tests. diff --git a/tests/nvme/run_tests.py b/tests/nvme/run_tests.py deleted file mode 100644 index 8bc43f4..0000000 --- a/tests/nvme/run_tests.py +++ /dev/null @@ -1,425 +0,0 @@ -"""Compare fix-only Linux NVMe preparation in parallel, isolated chroot fixtures. - -Requires Linux root, Python 3.10+ and existing userspace tools. The extension's -literal _LINUX_SCRIPT is read with AST, never imported. Reference and candidate -scripts run on separate fake guest filesystems with stubbed device commands; -there are no mounts, real guest disks, Azure calls or SSH connections. - -CLI: --reference PATH --report NEW_JSON [--evidence-dir NEW_DIR] [--jobs N]. -Reports and evidence must be new and outside the checkout. Completed comparisons -return 0 when all cases pass or 1 when any case fails; argparse errors return 2. -An aborted setup/run can leave an incomplete report, which is not a pass. -See the adjacent README.md for dependencies, commands and evidence schemas. -""" - -from __future__ import annotations - -import argparse -import ast -from concurrent.futures import ThreadPoolExecutor, as_completed -from dataclasses import dataclass -from datetime import datetime, timezone -import hashlib -import json -import os -from pathlib import Path -import re -import shutil -import subprocess -import sys -import tempfile - - -STUB = r'''#!/bin/bash -name=${0##*/} -printf '%s %s\n' "$name" "$*" >> /commands.log -if [[ -f /fail-command && "$(< /fail-command)" == "$name" ]]; then exit 42; fi -case "$name" in - hostname) echo fixture-host ;; - uname) echo rescue-kernel ;; - modinfo|udevadm|azure-nvme-id) exit 0 ;; - lsinitramfs|lsinitrd) cat "$@" ;; - update-initramfs) - [[ -f /failed-rebuild ]] && exit 0 - for image in /boot/initrd.img-*; do echo 'nvme hv_pci' > "$image"; done ;; - dracut) - [[ -f /failed-rebuild ]] && exit 0 - for image in /boot/initramfs-*.img; do - [[ "$image" == *kdump* || "$image" == *rescue* ]] && continue - echo 'nvme hv_pci' > "$image" - done ;; - update-grub) echo generated-grub > /boot/grub/grub.cfg ;; - grub2-mkconfig) echo generated-grub > "$2" ;; - grubby) - if [[ "$1" == --info=ALL ]]; then cat /bls-args - else echo nvme_core.io_timeout=240 > /bls-args; fi ;; - findmnt) - case "${@: -1}" in - /) echo /dev/sdz1 ;; /boot) echo /dev/sdz3 ;; - /boot/efi) echo /dev/sdz4 ;; *) exit 1 ;; - esac ;; - lsblk) echo sdz ;; - blkid) - device=${@: -1} - case "$device" in - /dev/sda1|/dev/sdz1) uuid=root-uuid ;; - /dev/sda2|/dev/sdz2) uuid=swap-uuid ;; - /dev/sda3|/dev/sdz3) uuid=boot-uuid ;; - /dev/sda4|/dev/sdz4) uuid=efi-uuid ;; - /dev/sdb1|/dev/disk/azure/scsi1/lun0-part1|/dev/nvme2n5p1) uuid=data-uuid ;; - *) exit 2 ;; - esac - printf '%s: UUID="%s" TYPE="ext4"\n' "$device" "$uuid" ;; - *) exit 1 ;; -esac -''' -DISTROS = ('ubuntu', 'debian', 'redhat', 'rhel', 'centos', 'rocky', 'almalinux', - 'suse', 'sles', 'ol', 'azurelinux', 'mariner') -COMMANDS = ('hostname uname modinfo udevadm lsinitramfs lsinitrd update-initramfs ' - 'dracut update-grub grub2-mkconfig grubby findmnt lsblk blkid').split() -FSTAB = '''# Preserve unrelated and unresolved entries. -/dev/sda1 / ext4 defaults 0 1 -/dev/sda3 /boot ext4 defaults 0 2 -/dev/sda4 /boot/efi vfat defaults 0 2 -/dev/sda2 none swap sw 0 0 -/dev/sdb1 /data xfs defaults 0 2 -/dev/disk/azure/scsi1/lun0-part1 /azure-data xfs defaults 0 2 -/dev/sdc1 /unavailable xfs defaults 0 2 -UUID=stable /stable ext4 defaults 0 2 -PARTUUID=part /part ext4 defaults 0 2 -/dev/mapper/rootvg-homelv /home xfs defaults 0 2 -/dev/disk/azure/resource-part1 /mnt/resource ext4 defaults 0 2 -''' - - -@dataclass(frozen=True) -class Case: - """Immutable distro/driver/mode/scenario key used by fixtures and evidence paths.""" - distro: str - state: str - mode: str - scenario: str = 'normal' - - @property - def name(self) -> str: - """Return the stable distro/state/mode/scenario identifier and relative path.""" - return '/'.join((self.distro, self.state, self.mode, self.scenario)) - - -def write(root: Path, name: str, text: str) -> None: - """Write a UTF-8 fixture file; callers supply names relative to root.""" - path = root / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding='utf-8') - - -def copy_tool(base: Path, binary: Path, destination: Path, ancestors: tuple[Path, ...] = ()) -> None: - """Copy a tool plus its shebang interpreter or ELF libraries into a chroot. - - Resolve symlinks and recursively copy absolute script interpreters. The ancestors - chain rejects interpreter cycles; missing tools and failed ldd calls abort setup. - """ - binary = binary.resolve() - if binary in ancestors: - raise RuntimeError(f'Cyclic fixture interpreter: {binary}') - destination.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(binary, destination) - header = binary.read_bytes().split(b'\n', 1)[0] - if header.startswith(b'#!'): - interpreter = Path(header[2:].decode().split()[0]) - if not interpreter.is_absolute(): - raise RuntimeError(f'Fixture interpreter must be absolute: {binary}') - # Recent coreutils packages use scripts with a multicall interpreter. - copy_tool(base, interpreter, base / str(interpreter).lstrip('/'), (*ancestors, binary)) - return - result = subprocess.run(['ldd', str(binary)], check=True, capture_output=True, text=True) - for library in re.findall(r'(?:=>\s+|^\s*)(/\S+)', result.stdout, re.MULTILINE): - target = base / library.lstrip('/') - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(Path(library).resolve(), target) - - -def prepare_base(base: Path) -> None: - """Build the reusable userspace base and logged synthetic device-command stubs. - - Copy existing host tools only; do not install packages or run real Azure/device - commands. Missing prerequisites raise an error before fixtures can be accepted. - """ - binaries: dict[str, Path] = {} - for tool in 'bash cat mkdir touch grep sed cp rm mv awk tee diff find sort readlink'.split(): - binary = shutil.which(tool) - if binary is None: - raise RuntimeError(f'Missing fixture tool: {tool}') - binaries[tool] = Path(binary) - for tool, binary in binaries.items(): - copy_tool(base, binary, base / 'bin' / tool) - for name in COMMANDS: - write(base, f'bin/{name}', STUB) - (base / 'bin' / name).chmod(0o755) - - -def fixture(base: Path, root: Path, case: Case, script: str, original: bool) -> None: - """Populate one private fake guest from the hard-linked userspace base. - - Case fields select driver contents, release files, boot arguments and failure - injection. original=True supplies guest-1 through uname; the candidate retains - the rescue-kernel stub to exercise installed-guest-kernel discovery. - """ - shutil.copytree(base, root, copy_function=os.link) - for directory in ('etc/default', 'etc/udev/rules.d', 'boot/grub', 'boot/grub2', - 'lib/modules/guest-1', 'dev', 'tmp'): - (root / directory).mkdir(parents=True, exist_ok=True) - for name, value in { - 'dev/null': '', 'commands.log': '', 'bls-args': '', 'run.sh': script, - 'etc/os-release': f'ID={case.distro}\n', - 'etc/default/grub': 'GRUB_CMDLINE_LINUX_DEFAULT="quiet"\nGRUB_CMDLINE_LINUX="console=ttyS0"\nGRUB_ENABLE_BLSCFG=true\n', - 'etc/fstab': FSTAB, 'etc/fstab.new': 'stale interrupted content\n', - 'device-map': '/dev/sdb /dev/nvme2n5\n/dev/disk/azure/scsi1/lun0 /dev/nvme2n5\n', - 'lib/modules/guest-1/modules.builtin': 'kernel/drivers/nvme/host/nvme.ko\n' if case.state == 'builtin' else '', - }.items(): - write(root, name, value) - contents = {'missing': '', 'builtin': '', 'ready': 'nvme hv_pci', - 'no-hvpci': 'nvme', 'no-nvme': 'hv_pci'}[case.state] - for image in ('initrd.img-guest-1', 'initramfs-guest-1.img', 'initramfs-guest-2.img'): - write(root, f'boot/{image}', contents + '\n') - for image in ('initramfs-kdump.img', 'initramfs-rescue.img'): - write(root, f'boot/{image}', 'excluded\n') - if original: - (root / 'bin/uname').unlink() - write(root, 'bin/uname', '#!/bin/bash\necho guest-1\n') - (root / 'bin/uname').chmod(0o755) - scenario = case.scenario - if scenario == 'no-grubby': - (root / 'bin/grubby').unlink() - elif scenario in ('bls-ready', 'defaults-ready', 'grub2-ready', 'grub-ready'): - target = {'bls-ready': 'bls-args', 'defaults-ready': 'etc/default/grub', - 'grub2-ready': 'boot/grub2/grub.cfg', 'grub-ready': 'boot/grub/grub.cfg'}[scenario] - with (root / target).open('a') as stream: - stream.write('\nnvme_core.io_timeout=240\n') - elif scenario.startswith('utils-'): - write(root, 'bin/azure-nvme-id', STUB) - (root / 'bin/azure-nvme-id').chmod(0o755) - if scenario != 'utils-missing-rules': - directory = {'utils-etc': 'etc', 'utils-lib': 'lib', 'utils-usrlib': 'usr/lib'}[scenario] - write(root, f'{directory}/udev/rules.d/80-azure-disk.rules', '') - elif scenario == 'fallback-ready': - write(root, 'etc/udev/rules.d/99-azure-nvme-fallback.rules', 'existing rule\n') - elif scenario == 'no-grub-file': - (root / 'etc/default/grub').unlink() - elif scenario == 'failed-rebuild': - write(root, 'failed-rebuild', '') - elif scenario.startswith('fail-'): - command = {'fail-update': 'update-initramfs', 'fail-dracut': 'dracut', 'fail-grub': 'grub2-mkconfig'}[scenario] - write(root, 'fail-command', command) - elif scenario == 'no-fstab-changes': - write(root, 'etc/fstab', 'UUID=stable / ext4 defaults 0 1\n') - elif scenario == 'no-release' or scenario.startswith('legacy-'): - (root / 'etc/os-release').unlink() - if scenario.startswith('legacy-'): - write(root, f'etc/{scenario.removeprefix("legacy-")}', '') - - -def normalized(text: str) -> str: - """Remove only declared offline diagnostics and unsupported reference usage flags. - - Use this for comparisons, never for the retained raw stdout/stderr evidence. - """ - text = re.sub(r'^\[INFO\] Offline guest:.*\n|^\[WARNING\] Cannot map guest device .*\n', '', text, flags=re.MULTILINE) - return text.replace('[-check] ', '').replace(' [-dryrun]', '') - - -def snapshot(root: Path, normalize_content: bool = True) -> dict[str, tuple[int, str]]: - """Capture fixture text and permission bits beneath etc, boot and tmp. - - normalize_content=False retains literal text for raw before/after evidence; - the default applies only the declared comparison normalization. - """ - return {str(path.relative_to(root)): (path.stat().st_mode & 0o7777, - normalized(path.read_text()) if normalize_content else path.read_text()) - for directory in ('etc', 'boot', 'tmp') for path in (root / directory).rglob('*') - if path.is_file()} - - -def compare(base: Path, parent: Path, case: Case, reference: str, action: str, - evidence_directory: Path | None = None) -> dict[str, str]: - """Run and validate both scripts for one case, returning passed/failed details. - - Each chroot phase has a 60-second timeout and an independently expected exit, - so equally broken scripts cannot pass by equality alone. Compare normalized - output, guest files, BLS arguments, mapping behavior and invalid-input nonmutation. - When evidence_directory is supplied, write a new schema-version-1 trace with - raw streams, commands and literal snapshots, including caught partial failures. - Existing evidence files are rejected rather than overwritten. - """ - phases: list[dict[str, object]] = [] - trace: dict[str, object] = {'schema_version': 1, 'kind': 'offline-stub-fixture', - 'case': case.name, 'phases': phases, 'boot_evidence': False} - try: - with tempfile.TemporaryDirectory(dir=parent, prefix='case-') as temporary: - roots = [Path(temporary) / name for name in ('original', 'action')] - outputs = [] - for index, (root, script) in enumerate(zip(roots, (reference, action))): - fixture(base, root, case, script, original=index == 0) - before = {name: value for name, value in snapshot(root).items() if not name.startswith('tmp/')} - args = {'fix': ['-fix'] if index == 0 else [], - 'invalid': ['-invalid']}[case.mode] - command = ['/usr/sbin/chroot', str(root), '/bin/bash', '/run.sh', *args] - phase: dict[str, object] = {'script': 'original' if index == 0 else 'candidate', - 'command': command, 'before': snapshot(root, False)} - phases.append(phase) - result = subprocess.run(command, - env={'PATH': '/bin', 'ALAR_NVME_DEVICE_MAP': '/device-map'}, - capture_output=True, text=True, timeout=60) - phase.update({'returncode': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr, - 'after': snapshot(root, False), 'commands': (root / 'commands.log').read_text()}) - expected_exit = 1 if case.mode == 'invalid' or case.scenario == 'no-release' else 0 - if result.returncode != expected_exit: - raise AssertionError(f'Unexpected script exit {result.returncode}; expected {expected_exit}: ' - f'{result.stdout}{result.stderr}') - outputs.append((result.returncode, normalized(result.stdout + result.stderr))) - if case.mode == 'invalid' or case.scenario == 'no-release': - after = {name: value for name, value in snapshot(root).items() if not name.startswith('tmp/')} - if before != after: - raise AssertionError('Invalid input modified protected guest files') - if outputs[0] != outputs[1]: - raise AssertionError(f'Original output: {outputs[0]}\nCandidate output: {outputs[1]}') - if snapshot(roots[0]) != snapshot(roots[1]): - raise AssertionError('Guest configuration or image contents differ') - if (roots[0] / 'bls-args').read_bytes() != (roots[1] / 'bls-args').read_bytes(): - raise AssertionError('BLS arguments differ') - log = (roots[1] / 'commands.log').read_text() - if re.search(r'^lsinitrd .*?(kdump|rescue)|^uname |^blkid -c /dev/null /dev/sd[abc]', log, re.MULTILINE): - raise AssertionError('Rescue identity used or excluded image inspected') - if case.mode == 'fix' and case.scenario == 'normal': - fstab = (roots[1] / 'etc/fstab').read_text() - for expected in ('UUID=swap-uuid none swap', 'UUID=data-uuid /data', - 'UUID=data-uuid /azure-data', '/dev/sdc1 /unavailable'): - if expected not in fstab: - raise AssertionError(f'Missing fstab assertion: {expected}') - outcome = {'case': case.name, 'status': 'passed'} - except (OSError, ValueError, AssertionError, subprocess.SubprocessError) as error: - outcome = {'case': case.name, 'status': 'failed', 'error': str(error)} - if evidence_directory is not None: - path = evidence_directory / f'{case.name}.json' - path.parent.mkdir(parents=True, exist_ok=True) - trace.update({'result': outcome, 'completed_at': datetime.now(timezone.utc).isoformat()}) - with path.open('x', encoding='utf-8') as stream: - json.dump(trace, stream, indent=2) - return outcome - - -def matrix() -> list[Case]: - """Return 65 fix-mode, release-detection, fallback and error cases.""" - cases = [Case(distro, state, 'fix') for distro in DISTROS - for state in ('missing', 'ready', 'builtin')] - cases += [Case(distro, state, 'fix') for distro in ('ubuntu', 'rhel') - for state in ('no-hvpci', 'no-nvme')] - scenarios = ('no-grubby', 'bls-ready', 'defaults-ready', 'grub2-ready', 'grub-ready', - 'utils-missing-rules', 'utils-etc', 'utils-lib', 'utils-usrlib', 'fallback-ready', - 'no-grub-file', 'failed-rebuild', 'fail-dracut', 'fail-grub', 'no-fstab-changes') - cases += [Case('rhel', 'missing', 'fix', scenario) for scenario in scenarios] - cases += [Case('ubuntu', 'missing', 'fix', scenario) for scenario in ('failed-rebuild', 'fail-update')] - cases += [Case('ignored', 'missing', 'fix', f'legacy-{release}') - for release in ('debian_version', 'SuSE-release', 'redhat-release', 'centos-release', 'rocky-release')] - cases += [Case('arch', 'missing', 'fix')] - return cases + [Case('ignored', 'missing', 'fix', 'no-release'), Case('ubuntu', 'missing', 'invalid')] - - -def verify_functions(reference: str, action: str) -> None: - """Verify unchanged timeout helpers/rules and required repair entrypoints. - - Repair functions have intentionally lost their non-fix branches; compare - their behavior through fixtures, not a claim of literal source identity. - """ - for name in ('check_azure_vm_utils', '_install_fallback_udev_rules', - 'check_nvme_driver', 'nvme_timeout_entries_ready', 'set_rhel7_timeout_defaults', - 'check_nvme_timeout', 'check_fstab'): - bodies = [] - for script in (reference, action): - match = re.search(rf'^{name}\(\) \{{\n.*?^\}}', script, re.MULTILINE | re.DOTALL) - if match is None: - raise ValueError(f'Missing original function: {name}') - bodies.append('\n'.join(line for line in match[0].splitlines() - if not line.lstrip().startswith('#') and 'echo "Usage:' not in line)) - if name in ('nvme_timeout_entries_ready', 'set_rhel7_timeout_defaults') and bodies[0] != bodies[1]: - raise ValueError(f'Shared timeout helper differs: {name}') - rules = [re.search(r"^_FALLBACK_UDEV_RULE=.*?^LABEL=.*?'$", text, re.MULTILINE | re.DOTALL) for text in (reference, action)] - if any(rule is None for rule in rules) or [rule[0] for rule in rules if rule is not None][0] != [rule[0] for rule in rules if rule is not None][1]: - raise ValueError('Fallback udev rules differ') - - -def main() -> int: - """Validate CLI paths, run bounded fixture workers and write the final report. - - Extract the reference literal without importing its module. Create an incomplete - report first; only a finished run records completed status, hashes, host details - and sorted case results. Optional evidence adds script copies, per-case traces - and per-distro summaries. Return 1 for completed runs with failed comparisons. - """ - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--reference', type=Path, required=True, help='Original extension _linux_script.py; read, never imported.') - parser.add_argument('--report', type=Path, required=True, help='New JSON report outside the checkout.') - parser.add_argument('--evidence-dir', type=Path, help='New external directory for raw per-case and per-distro evidence.') - parser.add_argument('--jobs', type=int, default=min(4, os.cpu_count() or 1)) - args = parser.parse_args() - if sys.platform != 'linux' or os.geteuid() != 0: - parser.error('Run as root inside Linux/WSL; fixtures use isolated chroot directories without mounts.') - if args.jobs < 1: - parser.error('--jobs must be positive') - report = args.report.resolve() - if report.is_relative_to(Path(__file__).resolve().parents[2]): - parser.error('Keep generated reports outside the checkout') - evidence = args.evidence_dir.resolve() if args.evidence_dir is not None else None - if evidence is not None and evidence.is_relative_to(Path(__file__).resolve().parents[2]): - parser.error('Keep raw evidence outside the checkout') - tree = ast.parse(args.reference.resolve().read_text(encoding='utf-8')) - values = [ast.literal_eval(node.value) for node in tree.body if isinstance(node, ast.Assign) - and any(isinstance(target, ast.Name) and target.id == '_LINUX_SCRIPT' for target in node.targets)] - if len(values) != 1 or not isinstance(values[0], str): - parser.error('Reference must define one literal _LINUX_SCRIPT string') - reference = values[0] - action = (Path(__file__).resolve().parents[2] / 'src/action_implementation/nvme-impl.sh').read_text() - verify_functions(reference, action) - report.parent.mkdir(parents=True, exist_ok=True) - with report.open('x', encoding='utf-8') as stream: - json.dump({'schema_version': 2, 'status': 'incomplete', 'mode': 'offline-fix-fixtures'}, stream) - if evidence is not None: - evidence.mkdir(parents=True, exist_ok=False) - (evidence / 'original-linux-script.sh').write_text(reference, encoding='utf-8') - (evidence / 'candidate-nvme-impl.sh').write_text(action, encoding='utf-8') - results = [] - with tempfile.TemporaryDirectory(prefix='alar-nvme-tests-') as temporary: - parent = Path(temporary) - prepare_base(parent / 'base') - with ThreadPoolExecutor(max_workers=args.jobs) as pool: - futures = [pool.submit(compare, parent / 'base', parent, case, reference, action, evidence) for case in matrix()] - for future in as_completed(futures): - result = future.result() - results.append(result) - if result['status'] == 'failed': - print(f"FAIL {result['case']}: {result['error']}", file=sys.stderr) - failed = sum(result['status'] == 'failed' for result in results) - document = {'schema_version': 2, 'status': 'completed', 'mode': 'offline-fix-fixtures', 'completed_at': datetime.now(timezone.utc).isoformat(), - 'workers': args.jobs, 'total': len(results), 'passed': len(results) - failed, 'failed': failed, - 'timeout_helpers_match': True, 'fallback_rules_match': True, - 'action_sha256': hashlib.sha256(action.encode()).hexdigest(), - 'reference_sha256': hashlib.sha256(reference.encode()).hexdigest(), 'results': sorted(results, key=lambda row: row['case']), - 'evidence_directory': str(evidence) if evidence is not None else None, - 'execution_host': {'wsl_distribution': os.environ.get('WSL_DISTRO_NAME'), 'python': sys.version, - 'os_release': Path('/etc/os-release').read_text()}} - if evidence is not None: - for distro in sorted({row['case'].split('/')[0] for row in results}): - rows = [row for row in document['results'] if row['case'].split('/')[0] == distro] - summary = {'kind': 'offline-stub-fixture-distro-summary', 'distro_id': distro, - 'execution_host': document['execution_host'], 'action_sha256': document['action_sha256'], - 'reference_sha256': document['reference_sha256'], 'results': rows, - 'raw_case_files': [f"{row['case']}.json" for row in rows], 'live_status': 'not run'} - with (evidence / f'{distro}.json').open('x', encoding='utf-8') as stream: - json.dump(summary, stream, indent=2) - report.write_text(json.dumps(document, indent=2) + '\n', encoding='utf-8') - print(f"{len(results) - failed}/{len(results)} passed; {args.jobs} parallel workers; report: {report}") - return int(failed != 0) - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/tests/nvme/test_efi_timeout.py b/tests/nvme/test_efi_timeout.py deleted file mode 100644 index 430f240..0000000 --- a/tests/nvme/test_efi_timeout.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Regress ALAR's RHEL 7 standalone EFI timeout handling in fake chroots. - -Linux root required; uses existing copied tools, never Azure, real mounts or disks. -Each case exercises the actual action's timeout function and helper bodies. -""" -import os -from pathlib import Path -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from run_tests import prepare_base, write - - -@unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required') -class EfiTimeoutTests(unittest.TestCase): - """Keep stale EFI/defaults, exact token checks and other loader layouts safe.""" - @classmethod - def setUpClass(cls): - """Read the repository action and copy existing userspace tools.""" - cls.tmp = tempfile.TemporaryDirectory(prefix='alar-efi-timeout-') - cls.addClassCleanup(cls.tmp.cleanup) - cls.base = Path(cls.tmp.name) / 'base' - prepare_base(cls.base) - repo = Path(__file__).resolve().parents[2] - cls.scripts = ((repo / 'src/action_implementation/nvme-impl.sh').read_text(),) - - def run_case(self, script, version='7.9', efi=True, ready=False, - token='', broken=False, redirect=False, failure=False, missing_defaults=False, silent_failure=False, other_kernel_missing=False): - """Run actual function definitions against synthetic boot entries and logged rebuilds.""" - temporary = tempfile.TemporaryDirectory(dir=self.tmp.name) - self.addCleanup(temporary.cleanup) - root = Path(temporary.name) / 'guest' - shutil.copytree(self.base, root) - target = '/boot/efi/EFI/redhat/grub.cfg' - write(root, 'etc/os-release', f'ID=rhel\nVERSION_ID="{version}"\n') - defaults = 'GRUB_CMDLINE_LINUX="quiet nvme_core.io_timeout=240 console=ttyS0"\n' - if not missing_defaults: - write(root, 'etc/default/grub', defaults) - entry = 'linuxefi /vmlinuz root=/dev/mapper/rootvg-rootlv quiet console=ttyS0' - write(root, 'boot/grub2/grub.cfg', entry + ' nvme_core.io_timeout=240\n') - if efi: - write(root, target.lstrip('/'), 'configfile /boot/grub2/grub.cfg\n' if redirect else - entry + (' nvme_core.io_timeout=240' if ready else (' ' + token if token else '')) + '\n' + (entry.replace('/vmlinuz', '/vmlinuz-older') + '\n' if other_kernel_missing else '')) - (root / 'etc/grub2-efi.cfg').symlink_to('/boot/efi/EFI/redhat/missing.cfg' if broken else target) - write(root, 'bin/grub2-mkconfig', '#!/bin/bash\necho "grub2-mkconfig $*" >> /commands.log\n' - + ('echo rebuild-error >&2; exit 42\n' if failure else 'exit 0\n' if silent_failure else - '. /etc/default/grub\nprintf "linuxefi /vmlinuz root=/dev/mapper/rootvg-rootlv %s\\n" "$GRUB_CMDLINE_LINUX" > "$2"\n')) - (root / 'bin/grub2-mkconfig').chmod(0o755) - write(root, 'commands.log', '') - write(root, 'dev/null', '') - functions = '\n\n'.join(re.findall(r'^(?:nvme_timeout_entries_ready|set_rhel7_timeout_defaults|check_nvme_timeout)\(\) \{\n.*?^\}', script, re.MULTILINE | re.DOTALL)) - write(root, 'run.sh', functions + '\ndistro=rhel\ncheck_nvme_timeout\n') - before = {str(path.relative_to(root)): path.read_bytes() for path in (root / 'boot').rglob('*') if path.is_file()} - result = subprocess.run(['/usr/sbin/chroot', str(root), '/bin/bash', '/run.sh'], - env={'PATH': '/bin'}, text=True, capture_output=True, timeout=30) - return root, result, before - - def each_source(self, **kwargs): - """Exercise the repository action, not a copied timeout algorithm.""" - return [self.run_case(script, **kwargs) for script in self.scripts] - - def test_stale_efi_is_not_ready_from_defaults_or_other_config(self): - """The exact live failure must not report readiness from the wrong files.""" - for root, result, _ in self.each_source(): - self.assertEqual(result.returncode, 0) - self.assertIn('[WARNING] nvme_core.io_timeout is not set to 240.', result.stdout) - self.assertNotIn('[INFO] nvme_core.io_timeout is set to 240.', result.stdout) - self.assertIn('grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg', (root/'commands.log').read_text()) - - def test_fix_rebuilds_standalone_efi_without_duplicate_default_argument(self): - """Repair the proven standalone EFI target even when desired defaults already have 240.""" - for root, result, _ in self.each_source(): - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg', (root/'commands.log').read_text()) - self.assertEqual((root/'etc/default/grub').read_text().count('nvme_core.io_timeout=240'), 1) - self.assertIn('quiet', (root/'etc/default/grub').read_text()) - self.assertIn('nvme_core.io_timeout=240', (root/'boot/efi/EFI/redhat/grub.cfg').read_text()) - - def test_ready_standalone_efi_is_idempotent(self): - """A ready EFI entry skips a needless rewrite.""" - for root, result, _ in self.each_source(ready=True): - self.assertNotIn('grub2-mkconfig', (root/'commands.log').read_text()) - self.assertIn('is set to 240.', result.stdout) - - def test_partial_or_wrong_argument_is_not_ready(self): - """2400 and a conflicting timeout must not be accepted as 240.""" - for token in ('nvme_core.io_timeout=2400', 'nvme_core.io_timeout=240 nvme_core.io_timeout=30'): - for root, result, _ in self.each_source(token=token): - self.assertEqual(result.returncode, 0) - self.assertIn('[WARNING] nvme_core.io_timeout is not set to 240.', result.stdout) - self.assertEqual((root/'boot/efi/EFI/redhat/grub.cfg').read_text().count('nvme_core.io_timeout='), 1) - self.assertIn('nvme_core.io_timeout=240 ', (root/'boot/efi/EFI/redhat/grub.cfg').read_text()) - - def test_broken_efi_target_is_explicit_error(self): - """A broken configured EFI link must not fall through to false readiness.""" - for root, result, _ in self.each_source(broken=True): - self.assertNotEqual(result.returncode, 0) - self.assertIn('[ERROR]', result.stdout) - self.assertEqual((root/'commands.log').read_text(), '') - - def test_modern_redirect_is_never_overwritten(self): - """A configfile stub must not become a full generated configuration.""" - for root, result, before in self.each_source(redirect=True): - self.assertNotEqual(result.returncode, 0) - self.assertIn('[ERROR]', result.stdout) - self.assertEqual((root/'boot/efi/EFI/redhat/grub.cfg').read_bytes(), before['boot/efi/EFI/redhat/grub.cfg']) - - def test_modern_release_keeps_original_behavior(self): - """RHEL8+/BLS selection remains outside this targeted old standalone EFI path.""" - for root, result, _ in self.each_source(version='9.8', redirect=True): - self.assertEqual(result.returncode, 0) - self.assertIn('is set to 240.', result.stdout) - self.assertEqual((root/'commands.log').read_text(), '') - - def test_bios_layout_keeps_original_behavior(self): - """Without a guest EFI configuration link retain the existing BIOS path.""" - for root, result, _ in self.each_source(efi=False): - self.assertEqual(result.returncode, 0) - self.assertIn('is set to 240.', result.stdout) - - def test_failed_efi_rebuild_is_error(self): - """An actual failed generator must not be hidden by desired defaults.""" - for root, result, _ in self.each_source(failure=True): - self.assertNotEqual(result.returncode, 0) - self.assertIn('[ERROR]', result.stdout) - - def test_missing_defaults_is_error(self): - """The fix cannot silently succeed without its expected defaults file.""" - for root, result, _ in self.each_source(missing_defaults=True): - self.assertNotEqual(result.returncode, 0) - self.assertIn('[ERROR]', result.stdout) - - def test_every_standalone_kernel_entry_requires_timeout(self): - """One ready entry cannot mask an older kernel without the required flag.""" - for root, result, _ in self.each_source(token='nvme_core.io_timeout=240', other_kernel_missing=True): - self.assertEqual(result.returncode, 0) - self.assertIn('[WARNING] nvme_core.io_timeout is not set to 240.', result.stdout) - self.assertIn('grub2-mkconfig', (root/'commands.log').read_text()) - - def test_successful_generator_without_repair_is_rejected(self): - """An exit-zero generator that leaves stale EFI entries is not a successful fix.""" - for root, result, _ in self.each_source(silent_failure=True): - self.assertNotEqual(result.returncode, 0) - self.assertIn('[ERROR] Failed to set nvme_core.io_timeout.', result.stdout) diff --git a/tests/nvme/test_offline.py b/tests/nvme/test_offline.py deleted file mode 100644 index baa4f0c..0000000 --- a/tests/nvme/test_offline.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Regressions for ALAR's fix-only interface and offline guest adapters. - -Run through unittest discovery as Linux root with the same copied-tool/chroot -prerequisites as run_tests.py. Other hosts skip this class, not certify it. -Tests use private fake guest directories, stub commands and the repository -candidate; they do not import the reference or use real disks/mounts/Azure/SSH. -See the adjacent README.md for the combined suite command and coverage. -""" - -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - -from run_tests import Case, fixture, prepare_base, snapshot, write - - -@unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required for isolated chroot fixtures') -class OfflineTests(unittest.TestCase): - """Verify guest identity, all kernels, safe swap mapping and explicit failures.""" - @classmethod - def setUpClass(cls): - """Create a shared temporary userspace base and read the candidate shell source.""" - cls.temporary = tempfile.TemporaryDirectory(prefix='alar-nvme-adapters-') - cls.addClassCleanup(cls.temporary.cleanup) - cls.base = Path(cls.temporary.name) / 'base' - prepare_base(cls.base) - cls.action = (Path(__file__).resolve().parents[2] / 'src/action_implementation/nvme-impl.sh').read_text() - - def setUp(self): - """Allocate a separate guest directory with automatic cleanup for each test.""" - self.directory = tempfile.TemporaryDirectory(dir=self.temporary.name) - self.addCleanup(self.directory.cleanup) - self.root = Path(self.directory.name) / 'guest' - - def prepare(self, distro='rhel', state='missing'): - """Build the selected fake guest layout for default-fix candidate execution.""" - fixture(self.base, self.root, Case(distro, state, 'fix'), self.action, original=False) - - def run_action(self, mapping='/device-map'): - """Execute the candidate in the test chroot with a 60-second timeout. - - mapping names a guest-visible map file; None omits ALAR_NVME_DEVICE_MAP entirely. - Return captured status/streams so tests can assert diagnostics and command use. - """ - environment = {'PATH': '/bin'} - if mapping is not None: - environment['ALAR_NVME_DEVICE_MAP'] = mapping - return subprocess.run(['/usr/sbin/chroot', str(self.root), '/bin/bash', '/run.sh'], - env=environment, capture_output=True, text=True, timeout=60) - - def log(self): - """Read the stub-command transcript from the current fake guest.""" - return (self.root / 'commands.log').read_text() - - def test_guest_builtin_kernel_not_rescue_kernel(self): - """A guest built-in driver must skip rebuilding without consulting rescue uname.""" - self.prepare('ubuntu', 'builtin') - result = self.run_action() - self.assertIn('NVMe driver is built into the kernel.', result.stdout) - self.assertNotIn('uname ', self.log()) - self.assertNotIn('update-initramfs ', self.log()) - - def test_all_guest_kernels_are_checked(self): - """A second installed guest kernel must be checked and repaired when needed.""" - self.prepare(state='builtin') - write(self.root, 'lib/modules/guest-2/modules.builtin', '') - self.run_action() - self.assertIn('modinfo -k guest-2 nvme', self.log()) - self.assertIn('dracut -f --regenerate-all', self.log()) - - def test_explicit_partition_mapping_covers_unmounted_swap(self): - """An explicit guest/rescue partition pair must resolve an unmounted swap entry.""" - self.prepare() - write(self.root, 'device-map', '/dev/sda2 /dev/nvme2n5p1\n') - self.run_action() - self.assertIn('UUID=data-uuid none swap', (self.root / 'etc/fstab').read_text()) - - def test_ambiguous_swap_is_not_looked_up_on_rescue_host(self): - """Unresolved swap must remain intact without probing its old name on the rescue.""" - self.prepare() - write(self.root, 'etc/fstab', 'UUID=stable / ext4 defaults 0 1\n/dev/sda2 none swap sw 0 0\n') - result = self.run_action(mapping=None) - self.assertIn('Cannot map guest device /dev/sda2', result.stderr) - self.assertIn('/dev/sda2 none swap', (self.root / 'etc/fstab').read_text()) - self.assertNotIn('blkid -c /dev/null /dev/sda2', self.log()) - - def test_invalid_map_is_reported_without_device_guessing(self): - """Malformed mapping must emit an error without speculative blkid calls.""" - self.prepare() - write(self.root, 'device-map', 'invalid-map\n') - result = self.run_action() - self.assertIn('[ERROR] Invalid device map entry:', result.stderr) - self.assertNotIn('blkid ', self.log()) - - def test_missing_map_is_reported(self): - """An unreadable explicitly selected map must emit a diagnostic.""" - self.prepare() - result = self.run_action(mapping='/missing-map') - self.assertIn('[ERROR] Cannot read device map:', result.stderr) - - def test_missing_guest_kernels_prevent_mutations(self): - """Missing installed guest kernels must fail before any stubbed repair command.""" - self.prepare() - shutil.rmtree(self.root / 'lib/modules/guest-1') - result = self.run_action() - self.assertEqual(result.returncode, 1) - self.assertIn('[ERROR] No installed guest kernels', result.stdout) - self.assertEqual(self.log(), '') - - def test_explicit_fix_matches_default(self): - """The optional fix flag and normal ALAR invocation must make identical repairs.""" - self.prepare() - explicit = Path(self.directory.name) / 'explicit' - shutil.copytree(self.root, explicit) - default_result = self.run_action() - explicit_result = subprocess.run( - ['/usr/sbin/chroot', str(explicit), '/bin/bash', '/run.sh', '-fix'], - env={'PATH': '/bin', 'ALAR_NVME_DEVICE_MAP': '/device-map'}, - capture_output=True, text=True, timeout=60) - self.assertEqual(default_result.returncode, 0) - self.assertEqual(explicit_result.returncode, 0) - self.assertEqual(default_result.stdout, explicit_result.stdout) - self.assertEqual(default_result.stderr, explicit_result.stderr) - self.assertEqual(snapshot(self.root, False), snapshot(explicit, False)) - self.assertIn('UUID=swap-uuid none swap', (explicit / 'etc/fstab').read_text()) - - def test_removed_modes_fail_before_any_changes(self): - """Removed flags must fail explicitly, never fall through into a repair.""" - self.prepare() - before = snapshot(self.root, False) - for arguments in (['-check'], ['-dryrun'], ['-check', '-fix'], ['-fix', '-dryrun']): - with self.subTest(arguments=arguments): - result = subprocess.run( - ['/usr/sbin/chroot', str(self.root), '/bin/bash', '/run.sh', *arguments], - env={'PATH': '/bin'}, capture_output=True, text=True, timeout=60) - self.assertEqual(result.returncode, 1) - self.assertIn('Usage: /run.sh [-fix]', result.stdout) - self.assertEqual(before, snapshot(self.root, False)) - self.assertEqual(self.log(), '') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/nvme/test_runner.py b/tests/nvme/test_runner.py deleted file mode 100644 index e551bb2..0000000 --- a/tests/nvme/test_runner.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Regressions for fix-only fixtures, raw evidence and interpreter copying. - -Run with unittest discovery as Linux root and existing chroot/userspace tools. -Other hosts skip this class; that is not guest acceptance. Tests reject equally -broken scripts and unexpected successful exits, preserve raw success/failure -records, and prove a shebang tool can run with its copied interpreter/libraries. -No Azure, SSH, real guest disks or mounts are used. See the adjacent README.md. -""" - -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - -from run_tests import Case, compare, copy_tool, matrix, prepare_base, write - - -@unittest.skipUnless(sys.platform == 'linux' and os.geteuid() == 0, 'Linux root required for isolated fixtures') -class RunnerTests(unittest.TestCase): - """Validate the harness and audit traces, not real Linux NVMe boot readiness.""" - def test_raw_case_evidence_keeps_streams_and_file_snapshots(self): - """Successful traces must retain both streams and literal before/after snapshots.""" - with tempfile.TemporaryDirectory(prefix='alar-raw-evidence-') as directory: - parent = Path(directory) - prepare_base(parent / 'base') - script = 'echo standard-output; echo standard-error >&2\n' - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'fix', 'no-fstab-changes'), script, script, parent / 'review') - self.assertEqual(result['status'], 'passed') - evidence = json.loads((parent / 'review/ubuntu/ready/fix/no-fstab-changes.json').read_text()) - self.assertFalse(evidence['boot_evidence']) - self.assertEqual(len(evidence['phases']), 2) - for phase in evidence['phases']: - self.assertEqual(phase['returncode'], 0) - self.assertEqual(phase['stdout'], 'standard-output\n') - self.assertEqual(phase['stderr'], 'standard-error\n') - self.assertIn('etc/fstab', phase['before']) - self.assertEqual(phase['before'], phase['after']) - - def test_failed_case_preserves_actual_exit_in_evidence(self): - """A caught shell failure must retain its real exit and failed result in evidence.""" - with tempfile.TemporaryDirectory(prefix='alar-failed-evidence-') as directory: - parent = Path(directory) - prepare_base(parent / 'base') - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'fix'), 'if then\n', 'if then\n', parent / 'review') - self.assertEqual(result['status'], 'failed') - evidence = json.loads((parent / 'review/ubuntu/ready/fix/normal.json').read_text()) - self.assertEqual(evidence['phases'][0]['returncode'], 2) - self.assertEqual(evidence['result']['status'], 'failed') - - def test_equal_shell_errors_are_failures(self): - """Matching shell syntax failures must still fail the expected-exit guard.""" - with tempfile.TemporaryDirectory(prefix='alar-equal-errors-') as directory: - parent = Path(directory) - prepare_base(parent / 'base') - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'fix'), 'if then\n', 'if then\n') - self.assertEqual(result['status'], 'failed') - self.assertIn('Unexpected script exit 2', result['error']) - - def test_equal_success_cannot_satisfy_expected_usage_failure(self): - """Matching exit0 results must not pass a case whose expected exit is 1.""" - with tempfile.TemporaryDirectory(prefix='alar-usage-errors-') as directory: - parent = Path(directory) - prepare_base(parent / 'base') - result = compare(parent / 'base', parent, Case('ubuntu', 'ready', 'invalid'), 'exit 0\n', 'exit 0\n') - self.assertEqual(result['status'], 'failed') - self.assertIn('expected 1', result['error']) - - def test_shebang_fixture_copies_interpreter(self): - """A copied script must run in its chroot with the absolute interpreter present.""" - bash = shutil.which('bash') - self.assertIsNotNone(bash) - with tempfile.TemporaryDirectory(prefix='alar-shebang-') as directory: - parent = Path(directory) - script = parent / 'script' - script.write_text(f'#!{bash}\nprintf copied-interpreter\n') - script.chmod(0o755) - root = parent / 'root' - copy_tool(root, script, root / 'bin/probe') - write(root, 'dev/null', '') - result = subprocess.run(['/usr/sbin/chroot', str(root), '/bin/probe'], - capture_output=True, text=True, timeout=10) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stdout, 'copied-interpreter') - - def test_matrix_only_contains_fix_and_invalid_input(self): - """Retain every fix scenario without advertising removed modes.""" - cases = matrix() - self.assertEqual(len(cases), 65) - self.assertEqual(len({case.name for case in cases}), 65) - self.assertEqual({case.mode for case in cases}, {'fix', 'invalid'}) - - -if __name__ == '__main__': - unittest.main() From 6b2d2dfecf8e595bead1bd902d7fed048854b41e Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Tue, 24 Nov 2026 21:56:41 -0600 Subject: [PATCH 4/9] Refuse NVMe without verified source-VM ADE eligibility Require a fresh root-owned source-VM check report covering OS and data disks before discovery or repair. Refuse encrypted or unknown guest partitions before ADE setup and keep other actions' recovery behavior unchanged. Keep the regression harness external and document the trusted report handoff. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 46 ++++++++++++++--- src/distro.rs | 8 +++ src/main.rs | 13 +++++ src/nvme.rs | 137 +++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 195 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index b3de0ec..cba728a 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,8 @@ The correct setup allows you to see the `GRUB Menu` as well get access to the sy #### nvme This action prepares the attached Linux guest for NVMe using the Linux preparation -logic from the Azure CLI `nvme-conversion` extension. Run it with `alar nvme`. +logic from the Azure CLI `nvme-conversion` extension. ADE-encrypted VMs are not +eligible, including VMs with ADE only on data disks. It preserves the original Linux script's checks and conditional fixes: built-in and initramfs driver detection, NVMe/Hyper-V PCI driver preparation, `nvme_core.io_timeout=240`, optional BLS updates, fallback Azure NVMe udev rules, @@ -86,14 +87,45 @@ Unresolved devices are left unchanged with a warning; the action does not guess that an old guest device name still identifies the same disk on the rescue VM. The original fstab backup remains `/etc/fstab.bak`. -ALAR always applies the conditional fixes. Within an already prepared guest -chroot, `bash /tmp/action_implementation/nvme-impl.sh -fix` is equivalent to -running the script without arguments. Check-only and dry-run modes are not -supported; no additional flags are added to ALAR's CLI. +Before recovery, a trusted operator or repair workflow must check the **original +VM**, not the rescue VM, using the updated `nvme-conversion` extension: + +```bash +az nvme-conversion check -g SOURCE_RG -n SOURCE_VM --controller-type NVMe \ + --ignore-os-check --ignore-sku-check --ignore-windows-version-check \ + -o json > nvme-eligibility.json +``` + +This performs read-only control-plane checks, not guest preparation. Skipping +OS/SKU checks does not bypass ADE verification. Preserve the full JSON output +without a `--query` projection. Transfer it securely to the rescue VM and install +it as a root-owned regular file that is not writable by group or others: + +```bash +sudo install -m 600 nvme-eligibility.json /root/nvme-eligibility.json +sudo ALAR_NVME_ELIGIBILITY_FILE=/root/nvme-eligibility.json alar nvme +``` + +The report must be no more than 15 minutes old; repeat the source-VM check +immediately before each invocation. Missing, invalid, failed, incomplete, stale +or ADE-positive reports stop `nvme` before disk discovery or any repair action, +including combined invocations such as `alar fstab,nvme`. Locally encrypted or +unidentified encrypted partitions are also refused before ADE unlocking. +Unlocking ADE or removing its extension does not decrypt the disks. Server-side +encryption and encryption at host are not ADE and are not excluded. + +The caller is trusted to associate the report with the actual source VM and +recovery disk and keep that VM's disk/encryption configuration unchanged during +the operation. The report is a private workflow handoff, not a signed Azure +attestation; ALAR cannot infer VM-wide encryption state from an offline disk. +Use `alar nvme` for the eligibility gate, not the internal action script directly. +The internal payload retains equivalent default/`-fix` behavior, with no check +or dry-run modes. No new ALAR CLI flags or Azure API dependencies are added. **Known framework limitation:** some Oracle Linux disk layouts are classified as -ADE-encrypted before ALAR reaches the action. This action does not change disk -discovery or ADE handling and cannot bypass that limitation. +ADE-encrypted before ALAR reaches the action. Those layouts remain refused; +this change does not replace the classifier or alter ADE recovery for other +actions. The original fix-path diagnostic and exit behavior is preserved: review the action output, not just ALAR's exit status, when evaluating preparation results. diff --git a/src/distro.rs b/src/distro.rs index bc0cd4e..da2d3dc 100644 --- a/src/distro.rs +++ b/src/distro.rs @@ -882,6 +882,14 @@ impl Distro { &partition_details ); + if let Err(e) = crate::nvme::ensure_not_ade( + &cli_info.actions, + partition_details.iter().any(|part| part.fstype.starts_with("crypt")), + ) { + error!("NVMe eligibility rejected: {e:#}"); + process::exit(1); + } + // at this point is is still not determined whether, if the fs_type is crypt, the disk needs to manually decrypted if Self::is_fs_crypt_detected(&partition_details) { /* diff --git a/src/main.rs b/src/main.rs index 8b49e4e..4e3b621 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,11 +35,24 @@ fn main() -> Result<()> { arguments.iter().for_each(|arg| debug!("{arg}")); } + if let Err(e) = nvme::ensure_not_ade(&cli_info.actions, !cli_info.ade_password.is_empty()) + .and_then(|_| nvme::validate_source_eligibility(&cli_info.actions)) + { + error!("NVMe eligibility rejected: {e:#}"); + process::exit(1); + } + // Create a new distro object // The distro object will be used to determine the distro of the VM we are trying to recover let distro = distro::Distro::new(&mut cli_info); info!("Distro details collected : {:#?}", distro); + if let Err(e) = nvme::ensure_not_ade(&cli_info.actions, distro.is_ade) { + error!("NVMe eligibility rejected: {e:#}"); + helper::cleanup(&distro, &cli_info)?; + process::exit(1); + } + // After we have collected all the required information we can start the actuall recover process. // If we have finished the recovery process it is important to rename the VG 'oldvg' back to 'rootvg'. // Otherwise the recovery VM might not boot up correctly diff --git a/src/nvme.rs b/src/nvme.rs index 472d5dc..a009ae1 100644 --- a/src/nvme.rs +++ b/src/nvme.rs @@ -1,14 +1,147 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the terms found in the LICENSE file in the root of this source tree. -use std::fs; +use std::collections::HashSet; +use std::env; +use std::fs::{self, File}; +use std::io::Read; +use std::os::unix::fs::MetadataExt; use std::path::Path; +use chrono::{DateTime, Duration, Utc}; use log::debug; use regex::Regex; -use anyhow::Result; +use serde::Deserialize; +use anyhow::{Context, Result, ensure}; use anyhow::anyhow; use std::sync::OnceLock; +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct SourceVmCheck { + overall_status: String, + target_controller_type: String, + vm_resource_id: String, + checks: EligibilityChecks, + nvme_eligibility: NvmeEligibility, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct EligibilityChecks { + ade_check: AdeCheck, +} + +#[derive(Deserialize)] +struct AdeCheck { + status: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct NvmeEligibility { + schema_version: u8, + source_vm_id: String, + checked_at: String, + os_disk: DiskEligibility, + data_disks: Vec, + data_disk_count: usize, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DiskEligibility { + id: String, + ade_enabled: bool, +} + +pub(crate) fn is_requested(actions: &str) -> bool { + actions.split(',').any(|action| action.trim().eq_ignore_ascii_case("nvme")) +} + +pub(crate) fn ensure_not_ade(actions: &str, encrypted_or_unknown: bool) -> Result<()> { + ensure!( + !is_requested(actions) || !encrypted_or_unknown, + "NVMe preparation is unsupported with ADE or unidentified encrypted partitions. \ + Unlocking a disk does not remove ADE." + ); + Ok(()) +} + +fn is_compute_resource_id(value: &str, resource_type: &str) -> bool { + let parts: Vec<_> = value.split('/').collect(); + parts.len() == 9 + && parts[0].is_empty() + && parts[1].eq_ignore_ascii_case("subscriptions") + && !parts[2].is_empty() + && parts[3].eq_ignore_ascii_case("resourceGroups") + && !parts[4].is_empty() + && parts[5].eq_ignore_ascii_case("providers") + && parts[6].eq_ignore_ascii_case("Microsoft.Compute") + && parts[7].eq_ignore_ascii_case(resource_type) + && !parts[8].is_empty() +} + +// The trusted repair workflow supplies this report for the original VM, not the rescue VM. +pub(crate) fn validate_eligibility_report(contents: &str, now: DateTime) -> Result<()> { + let report: SourceVmCheck = serde_json::from_str(contents).map_err(|error| { + anyhow!("Invalid or incomplete NVMe eligibility JSON at line {}, column {}", + error.line(), error.column()) + })?; + let eligibility = &report.nvme_eligibility; + ensure!( + report.overall_status == "passed" + && report.target_controller_type == "NVMe" + && report.checks.ade_check.status == "passed" + && eligibility.schema_version == 1, + "The source-VM report does not establish NVMe ADE eligibility." + ); + ensure!( + is_compute_resource_id(&report.vm_resource_id, "virtualMachines") + && report.vm_resource_id.eq_ignore_ascii_case(&eligibility.source_vm_id), + "The eligibility report has an invalid or inconsistent source VM identity." + ); + let checked_at = DateTime::parse_from_rfc3339(&eligibility.checked_at) + .context("The eligibility report has an invalid check timestamp")?; + let age = now.signed_duration_since(checked_at.with_timezone(&Utc)); + ensure!( + age >= Duration::seconds(-60) && age <= Duration::minutes(15), + "The eligibility report is expired or future-dated; repeat the source-VM check immediately before ALAR." + ); + ensure!( + eligibility.data_disk_count == eligibility.data_disks.len(), + "The eligibility report has an incomplete data-disk inventory." + ); + let mut ids = HashSet::new(); + for disk in std::iter::once(&eligibility.os_disk).chain(&eligibility.data_disks) { + ensure!( + !disk.ade_enabled && is_compute_resource_id(&disk.id, "disks"), + "ADE is enabled or a managed-disk identity is invalid; NVMe is refused." + ); + ensure!(ids.insert(disk.id.to_ascii_lowercase()), "Duplicate eligibility disk identity."); + } + Ok(()) +} + +pub(crate) fn validate_source_eligibility(actions: &str) -> Result<()> { + if !is_requested(actions) { + return Ok(()); + } + let path = env::var("ALAR_NVME_ELIGIBILITY_FILE").context( + "NVMe requires ALAR_NVME_ELIGIBILITY_FILE: a fresh source-VM check covering OS and data disks" + )?; + let file = File::open(&path).context("Cannot open the NVMe eligibility report")?; + let metadata = file.metadata().context("Cannot inspect the NVMe eligibility report")?; + ensure!( + metadata.is_file() && metadata.uid() == 0 && metadata.mode() & 0o022 == 0, + "The NVMe eligibility report must be a root-owned regular file, not writable by group or others." + ); + let mut contents = String::new(); + file.take(65_537).read_to_string(&mut contents) + .context("Cannot read the NVMe eligibility report")?; + ensure!(contents.len() <= 65_536, "The NVMe eligibility report exceeds 64 KiB."); + validate_eligibility_report(&contents, Utc::now()) +} + #[derive(Debug)] pub(crate) struct NvmeController { pub name: String, From 29983fae7a7585a41a618f0882dc4e089d14998f Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Wed, 25 Nov 2026 06:48:31 -0600 Subject: [PATCH 5/9] Remove external NVMe eligibility prerequisite from ALAR Restore standalone invocation and remove the JSON report input/parser. Refuse local BEK volumes, key files and unlocked mappings before discovery, including ADE-aware data-disk-only recovery with a plaintext OS disk. Keep encryption/probe-error refusal, other actions' ADE behavior and the external test harness; document the offline coverage boundary. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 52 ++++++++---------- src/main.rs | 2 +- src/nvme.rs | 149 ++++++++++++++-------------------------------------- 3 files changed, 60 insertions(+), 143 deletions(-) diff --git a/README.md b/README.md index cba728a..913ea48 100644 --- a/README.md +++ b/README.md @@ -87,38 +87,28 @@ Unresolved devices are left unchanged with a warning; the action does not guess that an old guest device name still identifies the same disk on the rescue VM. The original fstab backup remains `/etc/fstab.bak`. -Before recovery, a trusted operator or repair workflow must check the **original -VM**, not the rescue VM, using the updated `nvme-conversion` extension: +Run `alar nvme` directly. No external CLI command or eligibility report is +required. + +NVMe is refused before any requested repair when ADE credentials, an attached +`BEK VOLUME`, an existing recovery-key file or an unlocked ADE mapping is found +on the rescue VM. A BEK supplied by an ADE-aware repair workflow is also a +positive signal for data-disk-only ADE, even if the recovered OS disk is +plaintext. Detection uses volume/path metadata only: it does not mount the BEK +disk or read key contents. Probe failures also refuse NVMe rather than assume +that no key is present. + +Locally encrypted or unidentified encrypted recovery partitions are refused +before ADE unlocking. Unlocking ADE or removing its extension does not decrypt +the disks. Server-side encryption and encryption at host are not ADE. + +An offline disk alone cannot establish the state of unattached data disks. +BEK absence is not universal proof that the original VM is ADE-free, especially +in manual recovery where keys were not attached. The repair workflow/operator +must still ensure the source VM has no ADE on OS or data disks. Other actions' +ADE behavior is unchanged. Use `alar nvme`, not the internal action script +directly, for these local safeguards. -```bash -az nvme-conversion check -g SOURCE_RG -n SOURCE_VM --controller-type NVMe \ - --ignore-os-check --ignore-sku-check --ignore-windows-version-check \ - -o json > nvme-eligibility.json -``` - -This performs read-only control-plane checks, not guest preparation. Skipping -OS/SKU checks does not bypass ADE verification. Preserve the full JSON output -without a `--query` projection. Transfer it securely to the rescue VM and install -it as a root-owned regular file that is not writable by group or others: - -```bash -sudo install -m 600 nvme-eligibility.json /root/nvme-eligibility.json -sudo ALAR_NVME_ELIGIBILITY_FILE=/root/nvme-eligibility.json alar nvme -``` - -The report must be no more than 15 minutes old; repeat the source-VM check -immediately before each invocation. Missing, invalid, failed, incomplete, stale -or ADE-positive reports stop `nvme` before disk discovery or any repair action, -including combined invocations such as `alar fstab,nvme`. Locally encrypted or -unidentified encrypted partitions are also refused before ADE unlocking. -Unlocking ADE or removing its extension does not decrypt the disks. Server-side -encryption and encryption at host are not ADE and are not excluded. - -The caller is trusted to associate the report with the actual source VM and -recovery disk and keep that VM's disk/encryption configuration unchanged during -the operation. The report is a private workflow handoff, not a signed Azure -attestation; ALAR cannot infer VM-wide encryption state from an offline disk. -Use `alar nvme` for the eligibility gate, not the internal action script directly. The internal payload retains equivalent default/`-fix` behavior, with no check or dry-run modes. No new ALAR CLI flags or Azure API dependencies are added. diff --git a/src/main.rs b/src/main.rs index 4e3b621..1e24f3c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,7 +36,7 @@ fn main() -> Result<()> { } if let Err(e) = nvme::ensure_not_ade(&cli_info.actions, !cli_info.ade_password.is_empty()) - .and_then(|_| nvme::validate_source_eligibility(&cli_info.actions)) + .and_then(|_| nvme::ensure_no_rescue_ade_context(&cli_info.actions)) { error!("NVMe eligibility rejected: {e:#}"); process::exit(1); diff --git a/src/nvme.rs b/src/nvme.rs index a009ae1..42db031 100644 --- a/src/nvme.rs +++ b/src/nvme.rs @@ -1,59 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the terms found in the LICENSE file in the root of this source tree. -use std::collections::HashSet; -use std::env; -use std::fs::{self, File}; -use std::io::Read; -use std::os::unix::fs::MetadataExt; +use crate::constants; +use std::fs; +use std::io::ErrorKind; use std::path::Path; -use chrono::{DateTime, Duration, Utc}; +use std::process::Command; use log::debug; use regex::Regex; -use serde::Deserialize; use anyhow::{Context, Result, ensure}; use anyhow::anyhow; use std::sync::OnceLock; -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct SourceVmCheck { - overall_status: String, - target_controller_type: String, - vm_resource_id: String, - checks: EligibilityChecks, - nvme_eligibility: NvmeEligibility, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct EligibilityChecks { - ade_check: AdeCheck, -} - -#[derive(Deserialize)] -struct AdeCheck { - status: String, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct NvmeEligibility { - schema_version: u8, - source_vm_id: String, - checked_at: String, - os_disk: DiskEligibility, - data_disks: Vec, - data_disk_count: usize, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct DiskEligibility { - id: String, - ade_enabled: bool, -} - pub(crate) fn is_requested(actions: &str) -> bool { actions.split(',').any(|action| action.trim().eq_ignore_ascii_case("nvme")) } @@ -67,79 +25,48 @@ pub(crate) fn ensure_not_ade(actions: &str, encrypted_or_unknown: bool) -> Resul Ok(()) } -fn is_compute_resource_id(value: &str, resource_type: &str) -> bool { - let parts: Vec<_> = value.split('/').collect(); - parts.len() == 9 - && parts[0].is_empty() - && parts[1].eq_ignore_ascii_case("subscriptions") - && !parts[2].is_empty() - && parts[3].eq_ignore_ascii_case("resourceGroups") - && !parts[4].is_empty() - && parts[5].eq_ignore_ascii_case("providers") - && parts[6].eq_ignore_ascii_case("Microsoft.Compute") - && parts[7].eq_ignore_ascii_case(resource_type) - && !parts[8].is_empty() -} - -// The trusted repair workflow supplies this report for the original VM, not the rescue VM. -pub(crate) fn validate_eligibility_report(contents: &str, now: DateTime) -> Result<()> { - let report: SourceVmCheck = serde_json::from_str(contents).map_err(|error| { - anyhow!("Invalid or incomplete NVMe eligibility JSON at line {}, column {}", - error.line(), error.column()) - })?; - let eligibility = &report.nvme_eligibility; - ensure!( - report.overall_status == "passed" - && report.target_controller_type == "NVMe" - && report.checks.ade_check.status == "passed" - && eligibility.schema_version == 1, - "The source-VM report does not establish NVMe ADE eligibility." - ); - ensure!( - is_compute_resource_id(&report.vm_resource_id, "virtualMachines") - && report.vm_resource_id.eq_ignore_ascii_case(&eligibility.source_vm_id), - "The eligibility report has an invalid or inconsistent source VM identity." - ); - let checked_at = DateTime::parse_from_rfc3339(&eligibility.checked_at) - .context("The eligibility report has an invalid check timestamp")?; - let age = now.signed_duration_since(checked_at.with_timezone(&Utc)); - ensure!( - age >= Duration::seconds(-60) && age <= Duration::minutes(15), - "The eligibility report is expired or future-dated; repeat the source-VM check immediately before ALAR." - ); - ensure!( - eligibility.data_disk_count == eligibility.data_disks.len(), - "The eligibility report has an incomplete data-disk inventory." - ); - let mut ids = HashSet::new(); - for disk in std::iter::once(&eligibility.os_disk).chain(&eligibility.data_disks) { - ensure!( - !disk.ade_enabled && is_compute_resource_id(&disk.id, "disks"), - "ADE is enabled or a managed-disk identity is invalid; NVMe is refused." - ); - ensure!(ids.insert(disk.id.to_ascii_lowercase()), "Duplicate eligibility disk identity."); +pub(crate) fn bek_probe_detected( + status: Option, stdout: &[u8], stderr: &[u8], +) -> Result { + let matched = stdout.iter().any(|byte| !byte.is_ascii_whitespace()); + match status { + Some(0) if matched => Ok(true), + Some(2) if !matched && stderr.is_empty() => Ok(false), + _ => Err(anyhow!("Cannot determine ADE recovery-key presence: blkid probe failed or was incomplete.")), } - Ok(()) } -pub(crate) fn validate_source_eligibility(actions: &str) -> Result<()> { +pub(crate) fn ensure_no_rescue_ade_context(actions: &str) -> Result<()> { if !is_requested(actions) { return Ok(()); } - let path = env::var("ALAR_NVME_ELIGIBILITY_FILE").context( - "NVMe requires ALAR_NVME_ELIGIBILITY_FILE: a fresh source-VM check covering OS and data disks" - )?; - let file = File::open(&path).context("Cannot open the NVMe eligibility report")?; - let metadata = file.metadata().context("Cannot inspect the NVMe eligibility report")?; + for path in [ + constants::RESCUE_BEK_LINUX_PASS_PHRASE_FILE_NAME, + constants::RESCUE_TMP_LINUX_PASS_PHRASE_FILE_NAME, + constants::ADE_OSENCRYPT_PATH, + "/dev/mapper/osencrypt", + ] { + match fs::symlink_metadata(path) { + Ok(_) => { + return Err(anyhow!("An ADE recovery key or unlocked mapping is present. NVMe preparation is refused.")); + } + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => { + return Err(error).context("Cannot inspect local ADE recovery context"); + } + } + } + // This is the same BEK volume label used by ADE recovery, without mounting or reading its key. + let probe = Command::new("blkid") + .args(["-c", "/dev/null", "-t", "LABEL=BEK VOLUME", "-o", "device"]) + .output() + .context("Cannot inspect ADE recovery-key volumes with blkid")?; + let has_bek = bek_probe_detected(probe.status.code(), &probe.stdout, &probe.stderr)?; ensure!( - metadata.is_file() && metadata.uid() == 0 && metadata.mode() & 0o022 == 0, - "The NVMe eligibility report must be a root-owned regular file, not writable by group or others." + !has_bek, + "An ADE BEK recovery-key volume is attached. NVMe preparation is refused, even when the OS disk is plaintext." ); - let mut contents = String::new(); - file.take(65_537).read_to_string(&mut contents) - .context("Cannot read the NVMe eligibility report")?; - ensure!(contents.len() <= 65_536, "The NVMe eligibility report exceeds 64 KiB."); - validate_eligibility_report(&contents, Utc::now()) + Ok(()) } #[derive(Debug)] From f8c05e5aea46b2443728f36287a287f2241b3582 Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Wed, 25 Nov 2026 06:58:11 -0600 Subject: [PATCH 6/9] Remove unapproved extension references from ALAR Describe the NVMe action directly in usage and source comments, and name ALAR in the fallback rule's installer comment. Preserve Microsoft copyright and license notices and all operational behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 5 ++--- src/action_implementation/nvme-impl.sh | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 913ea48..ed83271 100644 --- a/README.md +++ b/README.md @@ -45,9 +45,8 @@ This action enables both the serialconsole and the GRUB serial. Incorrect vaules The correct setup allows you to see the `GRUB Menu` as well get access to the system via the `Azure Serial Console`. #### nvme -This action prepares the attached Linux guest for NVMe using the Linux preparation -logic from the Azure CLI `nvme-conversion` extension. ADE-encrypted VMs are not -eligible, including VMs with ADE only on data disks. +This action prepares the attached Linux guest for NVMe. ADE-encrypted VMs are +not eligible, including VMs with ADE only on data disks. It preserves the original Linux script's checks and conditional fixes: built-in and initramfs driver detection, NVMe/Hyper-V PCI driver preparation, `nvme_core.io_timeout=240`, optional BLS updates, fallback Azure NVMe udev rules, diff --git a/src/action_implementation/nvme-impl.sh b/src/action_implementation/nvme-impl.sh index f17e67c..69fd3e2 100644 --- a/src/action_implementation/nvme-impl.sh +++ b/src/action_implementation/nvme-impl.sh @@ -3,8 +3,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the terms found in the LICENSE file in the root of this source tree. -# Linux script from the nvme-conversion CLI extension, with offline guest -# kernel/device resolution and fix-only behavior for ALAR. +# Prepare a Linux guest for NVMe with offline kernel/device resolution. +# Fix-only action for ALAR. guest_kernel_version() { printf '%s\n' "$guest_kernel" @@ -168,7 +168,7 @@ check_azure_vm_utils() { # Provides: io_timeout=240s, /dev/disk/azure/root, /dev/disk/azure/data/by-lun/N # Does NOT provide: by-name, by-serial, by-index (those require azure-nvme-id binary) # Named 99- so that 80-azure-disk.rules takes precedence if azure-vm-utils is later installed. -_FALLBACK_UDEV_RULE='# Fallback Azure NVMe udev rules (installed by az nvme-conversion) +_FALLBACK_UDEV_RULE='# Fallback Azure NVMe udev rules (installed by ALAR) # Remove this file after installing azure-vm-utils (which provides 80-azure-disk.rules) ACTION!="add|change", GOTO="azure_nvme_fallback_end" SUBSYSTEM!="block", GOTO="azure_nvme_fallback_end" From aaebb79cc1aad4dec499b1155b0f67d216b41ce7 Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Wed, 25 Nov 2026 08:57:30 -0600 Subject: [PATCH 7/9] Verify NVMe boot preparation and propagate action failures Strengthen the existing driver, UUID and udev preparation paths and clean up on NVMe child failures without adding modes or a shipped test suite. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 13 +- src/action.rs | 30 ++- src/action_implementation/nvme-impl.sh | 294 ++++++++++++------------- src/main.rs | 9 +- 4 files changed, 187 insertions(+), 159 deletions(-) diff --git a/README.md b/README.md index ed83271..4821f58 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ The correct setup allows you to see the `GRUB Menu` as well get access to the sy #### nvme This action prepares the attached Linux guest for NVMe. ADE-encrypted VMs are not eligible, including VMs with ADE only on data disks. -It preserves the original Linux script's checks and conditional fixes: built-in +It performs Linux checks and conditional fixes: built-in and initramfs driver detection, NVMe/Hyper-V PCI driver preparation, `nvme_core.io_timeout=240`, optional BLS updates, fallback Azure NVMe udev rules, and SCSI-to-UUID fstab conversion. Existing ready configurations are skipped. @@ -61,6 +61,11 @@ rather than the running rescue kernel. Live udev reload is deferred to the guest next boot. Script coverage does not guarantee that every image or VM size supports NVMe. +Each installed guest kernel must have the actual NVMe PCI and Hyper-V PCI drivers +built in or present in its boot image. Missing images, failed inspections/rebuilds +and unresolved repair failures stop the action; ALAR cleans up before returning +the failure. A driver directory or `nvme-core` alone is not sufficient. + On RHEL/CentOS 7, a standalone EFI configuration selected by `/etc/grub2-efi.cfg` is checked and regenerated at that actual target. Every kernel entry must have exactly one `nvme_core.io_timeout=240` argument. Broken links, redirect stubs and @@ -82,8 +87,10 @@ Mappings can name whole disks or individual partitions. Use only independently identified attached guest devices, not rescue OS devices. For example, with the map saved on the rescue VM as `/tmp/nvme-device-map`, run `ALAR_NVME_DEVICE_MAP=/tmp/nvme-device-map alar nvme`. -Unresolved devices are left unchanged with a warning; the action does not guess -that an old guest device name still identifies the same disk on the rescue VM. +Multi-letter device names such as `/dev/sdaa1` are supported. If any legacy entry +cannot be resolved, the original fstab remains unchanged and the action fails. +The action does not guess that an old guest device name still identifies the +same disk on the rescue VM. The original fstab backup remains `/etc/fstab.bak`. Run `alar nvme` directly. No external CLI command or eligibility report is diff --git a/src/action.rs b/src/action.rs index f5b51f6..f91edc1 100644 --- a/src/action.rs +++ b/src/action.rs @@ -2,7 +2,7 @@ // Licensed under the terms found in the LICENSE file in the root of this source tree. use crate::{constants, helper}; -use anyhow::Result; +use anyhow::{Result, anyhow}; use log::debug; use std::io::Write; use std::{env, fs, io, process}; @@ -68,8 +68,10 @@ fn is_action_python_script(action_name: &str) -> bool { } pub(crate) fn run_repair_script(action_name: &str) -> Result<()> { + let nvme_action = action_name.trim().eq_ignore_ascii_case("nvme"); match env::set_current_dir(constants::RESCUE_ROOT) { Ok(_) => {} + Err(e) if nvme_action => return Err(e.into()), Err(e) => println!("Error in set current dir : {e}"), } @@ -80,7 +82,11 @@ pub(crate) fn run_repair_script(action_name: &str) -> Result<()> { }; let command = format!("chmod 500 {}", file_name); - helper::run_cmd(&command)?; + let permission_result = helper::run_cmd(&command); + if nvme_action && permission_result.is_err() { + env::set_current_dir("/")?; + } + permission_result?; println!("--- Action script output start ---"); io::stdout().flush().unwrap(); @@ -93,19 +99,27 @@ pub(crate) fn run_repair_script(action_name: &str) -> Result<()> { .arg(format!("{} 2>&1", file_name)) .stdout(process::Stdio::inherit()) .stderr(process::Stdio::inherit()) - .status()?; - - io::stdout().flush().unwrap(); - io::stderr().flush().unwrap(); - println!("--- Action script output end (exit code: {}) ---", status.code().unwrap_or(-1)); - io::stdout().flush().unwrap(); + .status(); // Get out of constants::RESCUE_ROOT, otherwise umount isn't possible for RESCUE_ROOT match env::set_current_dir("/") { Ok(_) => {} + Err(e) if nvme_action => return Err(e.into()), Err(e) => println!("Error in set current dir : {e}"), } + let status = status?; + io::stdout().flush().unwrap(); + io::stderr().flush().unwrap(); + println!("--- Action script output end (exit code: {}) ---", status.code().unwrap_or(-1)); + io::stdout().flush().unwrap(); + + if nvme_action && !status.success() { + return Err(anyhow!( + "NVMe action failed with exit code {}", + status.code().unwrap_or(-1) + )); + } Ok(()) } diff --git a/src/action_implementation/nvme-impl.sh b/src/action_implementation/nvme-impl.sh index 69fd3e2..bfe10bf 100644 --- a/src/action_implementation/nvme-impl.sh +++ b/src/action_implementation/nvme-impl.sh @@ -92,7 +92,7 @@ guest_blkid() { echo "[WARNING] Cannot map guest device $1 to an attached disk. Supply ALAR_NVME_DEVICE_MAP for unmounted or ambiguous devices." >&2 return 1 fi - command blkid -c /dev/null "$device" + command blkid -c /dev/null -s UUID -o value "$device" } distro="" @@ -183,8 +183,8 @@ KERNEL=="nvme*[0-9]n1", ENV{DEVTYPE}=="disk", SYMLINK+="disk/azure/root" KERNEL=="nvme*[0-9]n1p[0-9]*", ENV{DEVTYPE}=="partition", SYMLINK+="disk/azure/root-part%n" # Data disks: namespace ID 2+ maps to LUN = nsid - 2 -KERNEL=="nvme*[0-9]n*[0-9]", ENV{DEVTYPE}=="disk", ATTRS{nsid}!="1", PROGRAM="/bin/sh -ec '\''echo $(($(cat /sys/class/block/%k/nsid) - 2))'\''", SYMLINK+="disk/azure/data/by-lun/%c" -KERNEL=="nvme*[0-9]n*[0-9]p[0-9]*", ENV{DEVTYPE}=="partition", ATTRS{nsid}!="1", PROGRAM="/bin/sh -ec '\''echo $(($(cat /sys/class/block/$(echo %k | sed s/p[0-9]*$//)/nsid) - 2))'\''", SYMLINK+="disk/azure/data/by-lun/%c-part%n" +KERNEL=="nvme*[0-9]n*[0-9]", ENV{DEVTYPE}=="disk", ATTRS{nsid}=="?*", ATTRS{nsid}!="1", PROGRAM="/bin/sh -ec '\''echo $$((%s{nsid}-2))'\''", SYMLINK+="disk/azure/data/by-lun/%c" +KERNEL=="nvme*[0-9]n*[0-9]p[0-9]*", ENV{DEVTYPE}=="partition", ATTRS{nsid}=="?*", ATTRS{nsid}!="1", PROGRAM="/bin/sh -ec '\''echo $$((%s{nsid}-2))'\''", SYMLINK+="disk/azure/data/by-lun/%c-part%n" LABEL="azure_nvme_fallback_end"' @@ -197,7 +197,8 @@ _install_fallback_udev_rules() { fi echo "[INFO] Installing fallback NVMe udev rule at $_target" - echo "$_FALLBACK_UDEV_RULE" > "$_target" + mkdir -p /etc/udev/rules.d || return 1 + echo "$_FALLBACK_UDEV_RULE" > "$_target" || return 1 echo "[INFO] Offline guest: udev rules will load at the next boot." echo "[INFO] Fallback udev rule installed. Provides:" echo "[INFO] - io_timeout=240s for NVMe remote disks" @@ -207,94 +208,95 @@ _install_fallback_udev_rules() { } # Function to check if NVMe driver is in initrd/initramfs or built into the kernel -check_nvme_driver() { - echo "[INFO] Checking if NVMe driver is available for boot..." +nvme_module_builtin() { + grep -Eq "(^|/)($2)[.]ko$" "/lib/modules/$1/modules.builtin" 2>/dev/null +} - # Check if nvme is compiled directly into the kernel (built-in) - if grep -qw nvme "/lib/modules/$(guest_kernel_version)/modules.builtin" 2>/dev/null; then - echo "[INFO] NVMe driver is built into the kernel. No initramfs entry needed." +nvme_verify_boot_images() { + local tool="$1" nvme_builtin="$2" pci_builtin="$3" image listing missing=false + shift 3 + for image in "$@"; do + if ! listing=$("$tool" "$image" 2>&1); then + echo "[ERROR] Cannot inspect boot image $image." + return 2 + fi + if ! $nvme_builtin && ! grep -Eq '(^|[/[:space:]])nvme[.]ko([.](xz|gz|zst))?([[:space:]]|$)' <<< "$listing"; then + echo "[WARNING] NVMe PCI driver missing in $image." + missing=true + fi + if ! $pci_builtin && ! grep -Eq '(^|[/[:space:]])(hv_pci|pci[-_]hyperv)[.]ko([.](xz|gz|zst))?([[:space:]]|$)' <<< "$listing"; then + echo "[WARNING] Hyper-V PCI driver missing in $image." + missing=true + fi + done + ! $missing +} + +check_nvme_driver() { + local kernel="${1:-$(guest_kernel_version)}" nvme_builtin=false pci_builtin=false tool image status module + local candidates=() images=() + echo "[INFO] Checking NVMe and Hyper-V PCI boot drivers for $kernel..." + nvme_module_builtin "$kernel" nvme && nvme_builtin=true + nvme_module_builtin "$kernel" 'hv_pci|pci[-_]hyperv' && pci_builtin=true + if $nvme_builtin && $pci_builtin; then + echo "[INFO] NVMe and Hyper-V PCI drivers are built into kernel $kernel." return 0 fi - - echo "[INFO] NVMe is not built-in. Checking initrd/initramfs..." case "$distro" in ubuntu|debian) - _initramfs_ok=true - if ! lsinitramfs /boot/initrd.img-* 2>/dev/null | grep -q nvme; then - echo "[WARNING] NVMe driver not found in initrd/initramfs." - _initramfs_ok=false - fi - if ! lsinitramfs /boot/initrd.img-* 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then - echo "[WARNING] pci-hyperv/hv_pci driver not found in initrd/initramfs (required for Azure NVMe)." - _initramfs_ok=false - fi - if $_initramfs_ok; then - echo "[INFO] NVMe driver found in initrd/initramfs." - else - if modinfo -k "$guest_kernel" nvme &>/dev/null; then - echo "[INFO] NVMe module exists on disk." - fi - echo "[INFO] Adding NVMe/pci-hyperv drivers to initrd/initramfs..." - update-initramfs -u -k all - if lsinitramfs /boot/initrd.img-* | grep -q nvme; then - echo "[INFO] NVMe driver added successfully." - else - echo "[ERROR] Failed to add NVMe driver to initrd/initramfs." - fi - fi + tool=lsinitramfs + candidates=("/boot/initrd.img-$kernel") ;; - redhat|rhel|centos|rocky|almalinux|azurelinux|mariner|suse|sles|ol) - # Check ALL installed initramfs images, not just the running kernel - _nvme_missing=false - for _img in /boot/initramfs-*.img; do - [ -f "$_img" ] || continue - [[ "$_img" == *kdump* ]] && continue - [[ "$_img" == *rescue* ]] && continue - if ! lsinitrd "$_img" 2>/dev/null | grep -q nvme; then - echo "[WARNING] NVMe driver not found in $_img" - _nvme_missing=true - fi - if ! lsinitrd "$_img" 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then - echo "[WARNING] pci-hyperv/hv_pci driver not found in $_img (required for Azure NVMe)" - _nvme_missing=true + suse|sles) + tool=lsinitrd + candidates=("/boot/initrd-$kernel" "/boot/initramfs-$kernel.img") + ;; + redhat|rhel|centos|rocky|almalinux|azurelinux|mariner|ol) + tool=lsinitrd + candidates=("/boot/initramfs-$kernel.img") + ;; + *) + echo "[ERROR] Unsupported distribution for NVMe driver preparation." + return 1 + ;; + esac + for image in "${candidates[@]}"; do + [ -f "$image" ] && images+=("$image") + done + if [ "${#images[@]}" -eq 0 ]; then + echo "[ERROR] No usable boot image found for kernel $kernel." + return 1 + fi + if nvme_verify_boot_images "$tool" "$nvme_builtin" "$pci_builtin" "${images[@]}"; then + echo "[INFO] Required boot drivers verified for $kernel." + return 0 + else + status=$? + [ "$status" -eq 1 ] || return 1 + fi + + case "$distro" in + ubuntu|debian) + mkdir -p /etc/initramfs-tools || return 1 + touch /etc/initramfs-tools/modules || return 1 + for module in nvme pci-hyperv; do + if ! grep -qxF "$module" /etc/initramfs-tools/modules; then + printf '%s\n' "$module" >> /etc/initramfs-tools/modules || return 1 fi done - if ! $_nvme_missing; then - echo "[INFO] NVMe and pci-hyperv drivers found in initrd/initramfs." - else - if modinfo -k "$guest_kernel" nvme &>/dev/null; then - echo "[INFO] NVMe module exists on disk but is not in all initramfs images." - fi - echo "[INFO] Adding NVMe driver to initrd/initramfs (all kernels)..." - mkdir -p /etc/dracut.conf.d - echo 'add_drivers+=" nvme nvme-core pci-hyperv "' | tee /etc/dracut.conf.d/nvme.conf > /dev/null - dracut -f --regenerate-all - _verify_ok=true - for _img in /boot/initramfs-*.img; do - [ -f "$_img" ] || continue - [[ "$_img" == *kdump* ]] && continue - [[ "$_img" == *rescue* ]] && continue - if ! lsinitrd "$_img" 2>/dev/null | grep -q nvme; then - echo "[ERROR] NVMe driver still missing in $_img after rebuild." - _verify_ok=false - fi - if ! lsinitrd "$_img" 2>/dev/null | grep -qE 'hv_pci|pci.hyperv'; then - echo "[ERROR] pci-hyperv/hv_pci driver still missing in $_img after rebuild." - _verify_ok=false - fi - done - if $_verify_ok; then - echo "[INFO] NVMe driver added successfully." - else - echo "[ERROR] Failed to add NVMe driver to all initramfs images." - fi - fi + update-initramfs -u -k all || return 1 ;; *) - echo "[ERROR] Unsupported distribution for NVMe driver check." - return 1 + mkdir -p /etc/dracut.conf.d || return 1 + printf '%s\n' 'add_drivers+=" nvme nvme-core pci-hyperv "' > /etc/dracut.conf.d/nvme.conf || return 1 + dracut -f --regenerate-all || return 1 ;; esac + if ! nvme_verify_boot_images "$tool" "$nvme_builtin" "$pci_builtin" "${images[@]}"; then + echo "[ERROR] Required boot drivers remain unavailable after rebuilding $kernel." + return 1 + fi + echo "[INFO] Required boot drivers repaired and verified for $kernel." } # Function to check nvme_core.io_timeout parameter @@ -370,17 +372,17 @@ check_nvme_timeout() { echo "[INFO] Setting nvme_core.io_timeout to 240..." case "$distro" in ubuntu) - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true update-grub + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub || return 1 + GRUB_DISABLE_OS_PROBER=true update-grub || return 1 ;; debian) - sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true update-grub + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub || return 1 + GRUB_DISABLE_OS_PROBER=true update-grub || return 1 ;; suse|sles|opensuse*) if [ -f /etc/default/grub ]; then - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub || return 1 + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg || return 1 else echo "[ERROR] /etc/default/grub not found." return 1 @@ -395,13 +397,13 @@ check_nvme_timeout() { return 1 fi else - sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="nvme_core.io_timeout=240 /g' /etc/default/grub || return 1 + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg || return 1 fi # Update BLS entries if applicable (RHEL 8+, AlmaLinux 8+) if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then if command -v grubby &>/dev/null; then - grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" + grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" || return 1 echo "[INFO] Updated BLS entries via grubby." fi fi @@ -412,12 +414,12 @@ check_nvme_timeout() { ;; ol|azurelinux|mariner) if [ -f /etc/default/grub ]; then - sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub - GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.io_timeout=240 /g' /etc/default/grub || return 1 + GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/grub2/grub.cfg || return 1 # Update BLS entries if applicable (OL 8.10+) if grep -q "GRUB_ENABLE_BLSCFG=true" /etc/default/grub 2>/dev/null; then if command -v grubby &>/dev/null; then - grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" + grubby --update-kernel=ALL --args="nvme_core.io_timeout=240" || return 1 echo "[INFO] Updated BLS entries via grubby." fi fi @@ -439,74 +441,72 @@ check_nvme_timeout() { echo "[INFO] nvme_core.io_timeout set successfully (BLS entries)." else echo "[ERROR] Failed to set nvme_core.io_timeout." - if [ -n "$_rhel7_efi_config" ]; then return 1; fi + return 1 fi fi } # Function to check /etc/fstab for deprecated device names -check_fstab() { - echo "[INFO] Checking /etc/fstab for deprecated device names..." - # NOTE: /dev/mapper/* (LVM) and PARTUUID= paths survive NVMe conversion - # because they use UUID-based addressing underneath. Only /dev/sd* and - # /dev/disk/azure/scsi* paths break when disks move from SCSI to NVMe. - if grep -Eq '/dev/sd[a-z][0-9]*|/dev/disk/azure/scsi[0-9]*/lun[0-9]*' /etc/fstab; then - echo "[WARNING] /etc/fstab contains deprecated device names." - echo "[INFO] Replacing deprecated device names in /etc/fstab with UUIDs..." - - # Create a backup of the fstab file - cp /etc/fstab /etc/fstab.bak - - # Ensure fstab.new starts fresh (avoid stale leftovers from interrupted runs) - rm -f /etc/fstab.new - - # Use sed to replace device names with UUIDs - while read -r line; do - if [[ "$line" =~ ^[^#] ]]; then - device=$(echo "$line" | awk '{print $1}') - if [[ "$device" =~ ^/dev/sd[a-z][0-9]*$ ]]; then - uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') - if [ -n "$uuid" ]; then - newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") - echo "[INFO] Replaced $device with UUID=$uuid" - echo "$newline" >> /etc/fstab.new - else - echo "[WARNING] Could not find UUID for $device. Skipping." - echo "$line" >> /etc/fstab.new - fi - elif [[ "$device" =~ ^/dev/disk/azure/scsi[0-9]*/lun[0-9]* ]]; then - uuid=$(guest_blkid "$device" | awk -F\" '/UUID=/ {print $2}') - if [ -n "$uuid" ]; then - newline=$(echo "$line" | sed "s|$device|UUID=$uuid|g") - echo "[INFO] Replaced $device with UUID=$uuid" - echo "$newline" >> /etc/fstab.new - else - echo "[WARNING] Could not find UUID for $device. Skipping." - echo "$line" >> /etc/fstab.new - fi - else - echo "$line" >> /etc/fstab.new - fi +nvme_fstab_has_devices() { + awk '$0 !~ /^[[:space:]]*#/ && ($1 ~ /^\/dev\/sd[a-z]+[0-9]*$/ || $1 ~ /^\/dev\/disk\/azure\/scsi[0-9]+\/lun[0-9]+(-part[0-9]+)?$/) { found=1 } + END { exit !found }' "$1" +} + +nvme_migrate_fstab() { + local line device rest uuid missing=false + : > "$2" || return 1 + while IFS= read -r line || [ -n "$line" ]; do + read -r device rest <<< "$line" + if [[ "$device" =~ ^/dev/sd[a-z]+[0-9]*$ || "$device" =~ ^/dev/disk/azure/scsi[0-9]+/lun[0-9]+(-part[0-9]+)?$ ]]; then + if uuid=$(guest_blkid "$device") && [[ -n "$uuid" && "$uuid" != *[[:space:]]* ]]; then + line="${line/"$device"/UUID=$uuid}" + echo "[INFO] Resolved $device to UUID=$uuid." else - echo "$line" >> /etc/fstab.new + echo "[ERROR] Cannot resolve UUID for $device; leaving the original fstab unchanged." + missing=true fi - done < /etc/fstab - - # Replace the old fstab with the new fstab - mv /etc/fstab.new /etc/fstab + fi + printf '%s\n' "$line" >> "$2" || return 1 + done < "$1" + ! $missing +} - echo "[INFO] /etc/fstab updated with UUIDs. Original fstab backed up to /etc/fstab.bak" +check_fstab() { + echo "[INFO] Checking /etc/fstab for deprecated device names..." + if [ ! -r /etc/fstab ]; then + echo "[ERROR] Cannot read /etc/fstab." + return 1 + fi + if nvme_fstab_has_devices /etc/fstab; then + : else - echo "[INFO] /etc/fstab does not contain deprecated device names." + if [ "$?" -ne 1 ]; then + echo "[ERROR] Cannot inspect /etc/fstab." + return 1 + fi + echo "[INFO] /etc/fstab has no deprecated device names." + return 0 fi + + cp /etc/fstab /etc/fstab.bak || return 1 + rm -f /etc/fstab.new || return 1 + nvme_migrate_fstab /etc/fstab /etc/fstab.new || return 1 + mv /etc/fstab.new /etc/fstab || return 1 + if nvme_fstab_has_devices /etc/fstab; then + echo "[ERROR] Deprecated device names remain in /etc/fstab." + return 1 + fi + echo "[INFO] /etc/fstab updated with UUIDs; original saved as /etc/fstab.bak." } # Run the checks -check_azure_vm_utils +failed=false +check_azure_vm_utils || failed=true for guest_kernel in "${guest_kernels[@]}"; do - check_nvme_driver + check_nvme_driver || failed=true done -check_nvme_timeout -check_fstab - +check_nvme_timeout || failed=true +check_fstab || failed=true +if $failed; then echo "NVME_PREPARATION_RESULT:FAILED"; exit 1; fi +echo "NVME_PREPARATION_RESULT:READY" exit 0 diff --git a/src/main.rs b/src/main.rs index 1e24f3c..9f41bcd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -116,7 +116,14 @@ fn main() -> Result<()> { } else { for action_name in cli_info.actions.split(',') { debug!("Running action script: {}", action_name.trim()); - action::run_repair_script(action_name.trim())?; + if let Err(e) = action::run_repair_script(action_name.trim()) { + if nvme::is_requested(action_name) { + error!("NVMe preparation failed: {e:#}"); + mount::umount(constants::RESCUE_ROOT, true)?; + helper::cleanup(&distro, &cli_info)?; + } + return Err(e); + } } } From caa224f7730454a27d9d2a47898bce6765f6c818 Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Wed, 25 Nov 2026 11:58:47 -0600 Subject: [PATCH 8/9] Clarify creation-time BEK provisioning for NVMe recovery Document the live-verified manual-attachment boundary and link the Microsoft automatic-BEK workflow. Runtime code remains unchanged from the native ARM64/x64 and genuine ADE-refusal tested candidate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 4821f58..4fe60e4 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,10 @@ plaintext. Detection uses volume/path metadata only: it does not mount the BEK disk or read key contents. Probe failures also refuse NVMe rather than assume that no key is present. +Attaching an encrypted disk to an already-created rescue VM does not by itself +guarantee a BEK volume. The documented [automatic BEK workflow](https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/linux/unlock-encrypted-linux-disk-offline-repair) +attaches the encrypted disk when creating the rescue VM. + Locally encrypted or unidentified encrypted recovery partitions are refused before ADE unlocking. Unlocking ADE or removing its extension does not decrypt the disks. Server-side encryption and encryption at host are not ADE. From 9520828331b8a77ef527de6d949d39cbcf9f1795 Mon Sep 17 00:00:00 2001 From: Jonathan Brenes Date: Thu, 26 Nov 2026 13:28:23 -0600 Subject: [PATCH 9/9] fix(nvme): identify real guest kernels Use installed kernel package files and boot references instead of module directories. Ignore module-only kmod-kvdo and debug/header artifacts while preserving genuine missing-image failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 6 ++ src/action_implementation/nvme-impl.sh | 95 +++++++++++++++++++++++--- 2 files changed, 91 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4fe60e4..e1a09fe 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,12 @@ rather than the running rescue kernel. Live udev reload is deferred to the guest next boot. Script coverage does not guarantee that every image or VM size supports NVMe. +Guest kernel releases come from installed kernel package file lists and guest +boot images/configuration. A module-only directory, such as an older directory +populated by RHEL's `kmod-kvdo`, is not treated as another installed kernel. +Package-query failures stop preparation; missing images for genuine installed +or boot-referenced kernels are not silently skipped. + Each installed guest kernel must have the actual NVMe PCI and Hyper-V PCI drivers built in or present in its boot image. Missing images, failed inspections/rebuilds and unresolved repair failures stop the action; ALAR cleans up before returning diff --git a/src/action_implementation/nvme-impl.sh b/src/action_implementation/nvme-impl.sh index bfe10bf..36684de 100644 --- a/src/action_implementation/nvme-impl.sh +++ b/src/action_implementation/nvme-impl.sh @@ -135,16 +135,91 @@ else fi echo "[INFO] Operating system detected: $distro" -# uname reports the rescue kernel even inside a chroot. Check the original -# driver logic against every installed guest kernel instead. -guest_kernels=() -for modules_dir in /lib/modules/*; do - [ -d "$modules_dir" ] && guest_kernels+=("${modules_dir##*/}") -done -if [ "${#guest_kernels[@]}" -eq 0 ]; then - echo "[ERROR] No installed guest kernels found in /lib/modules." - exit 1 -fi +# Module packages can populate an older /lib/modules directory without +# installing that kernel. Package file lists also retain missing boot images. +collect_guest_kernels() { + local image_files packages status package files config field image rest kernel existing duplicate + case "$distro" in + ubuntu|debian) + if ! packages=$(dpkg-query -W -f '${db:Status-Status} ${binary:Package}\n' 'linux-image-*' 2>&1); then + echo "[ERROR] Cannot query installed guest kernel packages: $packages" >&2 + return 1 + fi + image_files="" + while read -r status package; do + [ "$status" = installed ] || continue + if ! files=$(dpkg-query -L "$package" 2>&1); then + echo "[ERROR] Cannot query guest kernel files for $package: $files" >&2 + return 1 + fi + image_files+=$'\n'"$files" + done <<< "$packages" + ;; + *) + if ! image_files=$(rpm -qa --qf '[%{FILENAMES}\n]' 'kernel*' 2>&1); then + echo "[ERROR] Cannot query installed guest kernel files: $image_files" >&2 + return 1 + fi + ;; + esac + for image in /boot/vmlinuz-* /boot/vmlinux-* /lib/modules/*/vmlinuz /usr/lib/modules/*/vmlinuz; do + [ -f "$image" ] && image_files+=$'\n'"$image" + done + for config in /boot/grub/grub.cfg /boot/grub2/grub.cfg /etc/grub2-efi.cfg /boot/loader/entries/*.conf; do + [ -f "$config" ] || continue + if [ ! -r "$config" ]; then + echo "[ERROR] Cannot read guest boot configuration: $config" >&2 + return 1 + fi + while read -r field image rest || [ -n "$field" ]; do + case "$field" in + linux|linuxefi|linux16) + image_files+=$'\n'"/boot/${image##*/}" + ;; + esac + done < "$config" + done + guest_kernels=() + while IFS= read -r image; do + image="${image#\"}" + image="${image%\"}" + image="${image#\'}" + image="${image%\'}" + case "$image" in + /lib/modules/*/vmlinuz|/usr/lib/modules/*/vmlinuz) + kernel="${image%/vmlinuz}" + kernel="${kernel##*/}" + ;; + /boot/vmlinuz-*|/boot/vmlinux-*|/vmlinuz-*|/vmlinux-*) + kernel="${image##*/}" + kernel="${kernel#*-}" + ;; + *) continue ;; + esac + case "$kernel" in + ""|0-rescue-*) continue ;; + esac + if [[ ! "$kernel" =~ ^[a-zA-Z0-9_.+~-]+$ ]]; then + echo "[ERROR] Invalid guest kernel release in boot image path: $image" >&2 + return 1 + fi + if [ ! -d "/lib/modules/$kernel" ]; then + echo "[ERROR] No guest module directory found for kernel $kernel." >&2 + return 1 + fi + duplicate=false + for existing in "${guest_kernels[@]}"; do + [ "$existing" = "$kernel" ] && duplicate=true && break + done + $duplicate || guest_kernels+=("$kernel") + done <<< "$image_files" + if [ "${#guest_kernels[@]}" -eq 0 ]; then + echo "[ERROR] No installed or boot-referenced guest kernels found." >&2 + return 1 + fi +} + +collect_guest_kernels || exit 1 # Function to check if azure-vm-utils is installed check_azure_vm_utils() { echo "[INFO] Checking for azure-vm-utils..."