"""get_disks: the overall SMART verdict, and the md array each disk belongs to. smartctl prints the overall verdict only for ``-H``; ``-i`` (identity) and ``-A`` (attributes) never do. The fake host below answers smartctl the way it builds its output: one section per flag asked for, so a command without ``-H`` gets no verdict. The sections are in the form smartmontools 7.3 prints them (ATA, NVMe and SCSI), cut to the lines that matter here; they are not recorded from a device. """ from __future__ import annotations import json import re import pytest from napalm_openmediavault.openmediavault import OpenMediaVaultDriver, smart_health _BANNER = ( "smartctl 7.3 2022-02-28 r5338 [x86_64-linux-6.1.0-26-amd64] (local build)\n" "Copyright (C) 2002-22, Bruce Allen, Christian Franke, www.smartmontools.org\n" ) ATA_INFO = """\ === START OF INFORMATION SECTION === Model Family: HGST Ultrastar 7K6 Device Model: HGST HUS726T6TALE6L4 Serial Number: K1AAAAAA Rotation Rate: 7200 rpm SMART support is: Available - device has SMART capability. SMART support is: Enabled """ ATA_PASSED = "SMART overall-health self-assessment test result: PASSED\n" ATA_FAILED = ( "SMART overall-health self-assessment test result: FAILED!\n" "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n" ) ATA_ATTRIBUTES = """\ SMART Attributes Data Structure revision number: 16 Vendor Specific SMART Attributes with Thresholds: ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE 1 Raw_Read_Error_Rate 0x000b 100 100 016 Pre-fail Always - 0 194 Temperature_Celsius 0x0002 176 176 000 Old_age Always - 34 (Min/Max 20/45) """ NVME_INFO = """\ === START OF INFORMATION SECTION === Model Number: Samsung SSD 980 PRO 1TB Serial Number: S5AAAAAAAAAAAAA """ NVME_PASSED = "SMART overall-health self-assessment test result: PASSED\n" NVME_ATTRIBUTES = """\ SMART/Health Information (NVMe Log 0x02) Critical Warning: 0x00 Temperature: 41 Celsius """ SCSI_OK = "SMART Health Status: OK\n" SCSI_PREDICTED = ( "SMART Health Status: FIRMWARE IMPENDING FAILURE TOO MANY BLOCK REASSIGNS [asc=5d, ascq=64]\n" ) USB_NO_SMART = ( "SMART support is: Unavailable - device lacks SMART capability.\n" "\n" "A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n" ) def smartctl(flags: str, info: str, health: str, attributes: str) -> str: """What ``smartctl -`` prints: the banner, then one section per flag.""" out = _BANNER + "\n" if "i" in flags: out += info + "\n" if "H" in flags or "A" in flags: out += "=== START OF READ SMART DATA SECTION ===\n" if "H" in flags: out += health + "\n" if "A" in flags: out += attributes return out class Nas: """The NAS as ``_send`` and ``_sudo`` see it: lsblk, /proc/mdstat and smartctl.""" def __init__(self, disks: dict[str, tuple[str, str, str, str]], mdstat: str = "") -> None: #: name -> (tran, info, health, attributes) self.disks = disks self.mdstat = mdstat self.commands: list[str] = [] def send(self, command: str, read_timeout: float = 100) -> str: self.commands.append(command) if command.startswith("lsblk "): return json.dumps( { "blockdevices": [ { "name": name, "size": 6001175126016, "type": "disk", "rota": tran != "nvme", "vendor": "", "model": "m", "serial": "s", "tran": tran, } for name, (tran, *_rest) in self.disks.items() ] } ) if command.startswith("cat /proc/mdstat"): return self.mdstat raise AssertionError(command) def sudo(self, command: str, read_timeout: float = 100) -> str: self.commands.append(command) m = re.match(r"smartctl -(\w+) /dev/(\w+)", command) assert m, command _tran, info, health, attributes = self.disks[m.group(2)] return smartctl(m.group(1), info, health, attributes) def _driver(nas: Nas) -> OpenMediaVaultDriver: driver = OpenMediaVaultDriver("nas", "admin", "p") driver._send = nas.send # type: ignore[method-assign] driver._sudo = nas.sudo # type: ignore[method-assign] return driver def _by_slot(nas: Nas) -> dict[str, dict]: return {d["slot"]: dict(d) for d in _driver(nas).get_disks()} # ── the overall verdict ───────────────────────────────────────────────────────── def test_a_passing_ata_disk_is_healthy(): nas = Nas({"sda": ("sata", ATA_INFO, ATA_PASSED, ATA_ATTRIBUTES)}) disk = _by_slot(nas)["/dev/sda"] assert disk["health"] == "healthy" assert (disk["temperature"], disk["rpm"]) == (34, 7200) def test_a_failing_ata_disk_is_failed(): nas = Nas({"sda": ("sata", ATA_INFO, ATA_FAILED, ATA_ATTRIBUTES)}) assert _by_slot(nas)["/dev/sda"]["health"] == "failed" def test_a_passing_nvme_disk_is_healthy(): nas = Nas({"nvme0n1": ("nvme", NVME_INFO, NVME_PASSED, NVME_ATTRIBUTES)}) disk = _by_slot(nas)["/dev/nvme0n1"] assert (disk["health"], disk["temperature"]) == ("healthy", 41) @pytest.mark.parametrize( ("output", "health"), [ (ATA_PASSED, "healthy"), (ATA_FAILED, "failed"), (NVME_PASSED, "healthy"), (SCSI_OK, "healthy"), (SCSI_PREDICTED, "failed"), (USB_NO_SMART, "unknown"), ("", "unknown"), # The attribute table's WHEN_FAILED column is no verdict. (ATA_ATTRIBUTES, "unknown"), ], ids=[ "ata-passed", "ata-failed", "nvme-passed", "scsi-ok", "scsi-predicted", "no-smart", "empty", "when-failed-column", ], ) def test_smart_health_reads_the_verdict_line_only(output, health): assert smart_health(_BANNER + output) == health # ── md membership ─────────────────────────────────────────────────────────────── MDSTAT = """\ Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10] md0 : active raid1 sdab1[1] sdaa1[0] 976630464 blocks super 1.2 [2/2] [UU] md1 : active raid1 sdb1[1] sdc1[0](F) 5860389888 blocks super 1.2 [2/1] [U_] md2 : active raid1 nvme0n1p1[0] nvme1n1[1] 976630464 blocks super 1.2 [2/2] [UU] md3 : active raid1 nvme2n11[0] nvme2n12[1] 976630464 blocks super 1.2 [2/2] [UU] unused devices: """ def test_a_disk_is_in_the_array_its_partition_or_itself_is_in(): names = ["sda", "sdaa", "sdc", "nvme0n1", "nvme1n1", "nvme2n1"] nas = Nas({n: ("sata", ATA_INFO, ATA_PASSED, ATA_ATTRIBUTES) for n in names}, MDSTAT) pools = {slot: d["pool"] for slot, d in _by_slot(nas).items()} assert pools == { "/dev/sda": "", # sdaa1 and sdab1 are not sda's "/dev/sdaa": "md0", "/dev/sdc": "md1", # a failed member is still a member "/dev/nvme0n1": "md2", "/dev/nvme1n1": "md2", "/dev/nvme2n1": "", # nvme2n11 is another namespace, not a partition } def test_mdstat_is_read_once_for_all_disks(): nas = Nas({n: ("sata", ATA_INFO, ATA_PASSED, ATA_ATTRIBUTES) for n in ("sda", "sdb")}, MDSTAT) _driver(nas).get_disks() assert sum(c.startswith("cat /proc/mdstat") for c in nas.commands) == 1