diff --git a/README.md b/README.md index a5799c1..e1a09fe 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,98 @@ 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. ADE-encrypted VMs are +not eligible, including VMs with ADE only on data disks. +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. +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. + +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 +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 +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`. +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 +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. + +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. + +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. + +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. 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. + #### grubfix This action is reinstalling `GRUB` and regenerates the `grub.cfg` file 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 new file mode 100644 index 0000000..36684de --- /dev/null +++ b/src/action_implementation/nvme-impl.sh @@ -0,0 +1,587 @@ +#!/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. + +# Prepare a Linux guest for NVMe with offline kernel/device resolution. +# Fix-only action for ALAR. + +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 -s UUID -o value "$device" +} + +distro="" + +# Function to display usage +usage() { + echo "Usage: $0 [-fix]" + exit 1 +} + +# Parse command line arguments +while [ $# -gt 0 ]; do + case "$1" in + -fix) + ;; + *) + 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" + +# 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..." + + 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." + _install_fallback_udev_rules + 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 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" +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}=="?*", 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"' + +_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 + + echo "[INFO] Installing fallback NVMe udev rule at $_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" + 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 +nvme_module_builtin() { + grep -Eq "(^|/)($2)[.]ko$" "/lib/modules/$1/modules.builtin" 2>/dev/null +} + +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 + case "$distro" in + ubuntu|debian) + tool=lsinitramfs + candidates=("/boot/initrd.img-$kernel") + ;; + 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 + update-initramfs -u -k all || 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 +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." + 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." + 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 || 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 || 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 || 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 + 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 || 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" || return 1 + 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 || 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" || return 1 + 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." + return 1 + fi + fi +} + +# Function to check /etc/fstab for deprecated device names +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 "[ERROR] Cannot resolve UUID for $device; leaving the original fstab unchanged." + missing=true + fi + fi + printf '%s\n' "$line" >> "$2" || return 1 + done < "$1" + ! $missing +} + +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 + 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 +failed=false +check_azure_vm_utils || failed=true +for guest_kernel in "${guest_kernels[@]}"; do + check_nvme_driver || failed=true +done +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/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/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/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/src/main.rs b/src/main.rs index 8b49e4e..9f41bcd 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::ensure_no_rescue_ade_context(&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 @@ -103,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); + } } } diff --git a/src/nvme.rs b/src/nvme.rs index 472d5dc..42db031 100644 --- a/src/nvme.rs +++ b/src/nvme.rs @@ -1,14 +1,74 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the terms found in the LICENSE file in the root of this source tree. +use crate::constants; use std::fs; +use std::io::ErrorKind; use std::path::Path; +use std::process::Command; use log::debug; use regex::Regex; -use anyhow::Result; +use anyhow::{Context, Result, ensure}; use anyhow::anyhow; use std::sync::OnceLock; +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(()) +} + +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.")), + } +} + +pub(crate) fn ensure_no_rescue_ade_context(actions: &str) -> Result<()> { + if !is_requested(actions) { + return Ok(()); + } + 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!( + !has_bek, + "An ADE BEK recovery-key volume is attached. NVMe preparation is refused, even when the OS disk is plaintext." + ); + Ok(()) +} + #[derive(Debug)] pub(crate) struct NvmeController { pub name: String,