fix(disks): raise on a failed lsblk, warn on failed smartctl calls
driver / standard (pull_request) Successful in 21s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m17s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / test (3.13) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 42s
driver / build (pull_request) Successful in 51s
driver / security (pull_request) Successful in 1m35s
CI / driver (pull_request) Successful in 3m26s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 21s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m17s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / test (3.13) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 42s
driver / build (pull_request) Successful in 51s
driver / security (pull_request) Successful in 1m35s
CI / driver (pull_request) Successful in 3m26s
driver / publish (pull_request) Skipped
get_disks swallowed a failed or garbled lsblk and returned [], the answer for a NAS without disks, so every disk vanished on a transient error. It now raises CommandErrorException; a failed /proc/mdstat read raises too instead of dropping every pool. A smartctl call that timed out, was refused by sudo or could not open the device was logged at debug level and read like a disk without SMART. It is now logged as a warning with the reason (exit status bits 0 and 1; the disk-state bits 2-7 are not a failed call). A disk whose verdict passed but that counts reallocated, pending or offline-uncorrectable sectors (ATA), grown defects (SAS), or sets a critical warning or counts media errors (NVMe) is reported as "warning", as the contract allows. get_disks shrinks below its baseline entries, which are tightened. Closes #16
This commit is contained in:
1 parent
099eef7f3e
commit
deb233617c
5 files changed
+271
-44
No files matched your search
@@ -23,6 +23,7 @@ import re
|
||||
from shlex import quote as _shlex_quote
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import FingerprintRule, StorageDriver
|
||||
from napalm_device_types.models import (
|
||||
DiskPoolDict,
|
||||
@@ -50,13 +51,29 @@ _HOSTNAME_MODULES = frozenset(
|
||||
_DIRTY_MODULES = "/var/lib/openmediavault/dirtymodules.json"
|
||||
|
||||
|
||||
#: Every block device, as JSON; sizes in bytes.
|
||||
_LSBLK = "lsblk -J -b -o NAME,SIZE,TYPE,ROTA,VENDOR,MODEL,SERIAL,TRAN 2>/dev/null"
|
||||
#: Identity, overall health verdict and attributes; ``-H`` alone prints the verdict.
|
||||
_SMARTCTL = "smartctl -iHA /dev/{name} 2>/dev/null"
|
||||
_SMARTCTL_TIMEOUT = 15
|
||||
#: smartctl's exit status bits 0 and 1: the command line did not parse (sudo's own
|
||||
#: refusal exits 1 as well) or the device could not be opened. Bits 2-7 describe the
|
||||
#: disk, not the call.
|
||||
_SMARTCTL_CALL_FAILED = 0b11
|
||||
#: The overall verdict of an ATA or NVMe disk: ``PASSED`` or ``FAILED!``.
|
||||
_SMART_VERDICT_RE = re.compile(r"^SMART overall-health self-assessment test result:\s*(\S+)", re.M)
|
||||
#: A SCSI/SAS disk's: ``OK``, or the failure it predicts.
|
||||
_SMART_SCSI_STATUS_RE = re.compile(r"^SMART Health Status:\s*(.+?)\s*$", re.M)
|
||||
_SMART_VERDICTS = {"PASSED": "healthy", "FAILED": "failed"}
|
||||
#: ATA attributes counting sectors the disk lost or could not read, and the raw value
|
||||
#: of each (the column after WHEN_FAILED).
|
||||
_SMART_ATA_DEGRADED = ("Reallocated_Sector_Ct", "Current_Pending_Sector", "Offline_Uncorrectable")
|
||||
_SMART_ATA_RAW_RE = re.compile(r"^\s*\d+\s+(\S+)\s+0x[0-9a-fA-F]+\s+(?:\S+\s+){6}(\d+)", re.M)
|
||||
#: An NVMe disk's own warning flags, and the media errors it counted.
|
||||
_SMART_NVME_CRITICAL_RE = re.compile(r"^Critical Warning:\s+0x([0-9a-fA-F]+)\s*$", re.M)
|
||||
_SMART_NVME_MEDIA_ERRORS_RE = re.compile(r"^Media and Data Integrity Errors:\s+([\d,]+)\s*$", re.M)
|
||||
#: A SCSI/SAS disk's reassigned blocks.
|
||||
_SMART_SCSI_DEFECTS_RE = re.compile(r"^Elements in grown defect list:\s+(\d+)\s*$", re.M)
|
||||
#: An ATA disk's temperature attribute, an NVMe disk's ``Temperature:`` line.
|
||||
_SMART_TEMP_RE = re.compile(
|
||||
r"(?:Temperature_Celsius|Current Temperature|Temperature:)[^\n]*?(\d+)\s*(?:Celsius|\(|$)"
|
||||
@@ -69,11 +86,22 @@ _MDSTAT_MEMBER_RE = re.compile(r"(\S+?)\[\d+\]")
|
||||
|
||||
|
||||
def smart_health(output: str) -> str:
|
||||
"""The overall SMART verdict in ``smartctl -H`` output.
|
||||
"""A disk's health from ``smartctl -iHA`` output.
|
||||
|
||||
``"healthy"`` or ``"failed"``; ``"unknown"`` when smartctl printed none (no
|
||||
SMART support, a USB bridge without pass-through).
|
||||
``"failed"`` when the overall verdict says so; ``"warning"`` when it passed but
|
||||
the disk counts lost or unreadable sectors (ATA reallocated, pending or offline
|
||||
uncorrectable sectors, SAS grown defects) or, for NVMe, sets a critical warning
|
||||
flag or counts media errors; ``"healthy"`` otherwise; ``"unknown"`` when
|
||||
smartctl printed no verdict (no SMART support, a USB bridge without
|
||||
pass-through).
|
||||
"""
|
||||
verdict = _smart_verdict(output)
|
||||
if verdict == "healthy" and _smart_degraded(output):
|
||||
return "warning"
|
||||
return verdict
|
||||
|
||||
|
||||
def _smart_verdict(output: str) -> str:
|
||||
verdict = _SMART_VERDICT_RE.search(output)
|
||||
if verdict:
|
||||
return _SMART_VERDICTS.get(verdict.group(1).rstrip("!"), "unknown")
|
||||
@@ -83,6 +111,22 @@ def smart_health(output: str) -> str:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _smart_degraded(output: str) -> bool:
|
||||
ata = any(
|
||||
name in _SMART_ATA_DEGRADED and int(raw) > 0
|
||||
for name, raw in _SMART_ATA_RAW_RE.findall(output)
|
||||
)
|
||||
critical = _SMART_NVME_CRITICAL_RE.search(output)
|
||||
media = _SMART_NVME_MEDIA_ERRORS_RE.search(output)
|
||||
defects = _SMART_SCSI_DEFECTS_RE.search(output)
|
||||
return (
|
||||
ata
|
||||
or bool(critical and int(critical.group(1), 16))
|
||||
or bool(media and int(media.group(1).replace(",", "")))
|
||||
or bool(defects and int(defects.group(1)))
|
||||
)
|
||||
|
||||
|
||||
def smart_temperature(output: str) -> int:
|
||||
"""A disk's temperature in Celsius from ``smartctl -A`` output; ``-1`` if none."""
|
||||
found = _SMART_TEMP_RE.search(output)
|
||||
@@ -236,7 +280,9 @@ class OpenMediaVaultDriver(OmvLocalAccountsMixin, StorageDriver, LinuxDriver):
|
||||
* size (int) - raw capacity in bytes
|
||||
* rpm (int) - rotational speed; ``0`` for SSD/NVMe
|
||||
* temperature (int) - temperature in Celsius; ``-1`` if unavailable
|
||||
* health (string) - ``"healthy"``, ``"failed"``, or ``"unknown"``
|
||||
* health (string) - ``"healthy"``, ``"warning"``, ``"failed"``, or
|
||||
``"unknown"`` (see :func:`smart_health`); a smartctl call that failed is
|
||||
logged as a warning and leaves the disk ``"unknown"``
|
||||
* pool (string) - md array name if member; empty string otherwise
|
||||
|
||||
Example::
|
||||
@@ -255,19 +301,13 @@ class OpenMediaVaultDriver(OmvLocalAccountsMixin, StorageDriver, LinuxDriver):
|
||||
"pool": "md1",
|
||||
},
|
||||
]
|
||||
|
||||
:raises CommandErrorException: when lsblk printed no device list.
|
||||
"""
|
||||
result: list[PhysicalDiskDict] = []
|
||||
|
||||
try:
|
||||
raw = self._send(
|
||||
"lsblk -J -b -o NAME,SIZE,TYPE,ROTA,VENDOR,MODEL,SERIAL,TRAN 2>/dev/null"
|
||||
)
|
||||
lsblk = _json.loads(raw)
|
||||
except Exception:
|
||||
return result
|
||||
|
||||
devices = self._lsblk()
|
||||
members = self._md_members()
|
||||
for dev in lsblk.get("blockdevices", []):
|
||||
for dev in devices:
|
||||
if dev.get("type") != "disk":
|
||||
continue
|
||||
name = dev.get("name", "")
|
||||
@@ -307,28 +347,56 @@ class OpenMediaVaultDriver(OmvLocalAccountsMixin, StorageDriver, LinuxDriver):
|
||||
|
||||
return result
|
||||
|
||||
def _smart(self, name: str, disk_type: str) -> tuple[str, int, int]:
|
||||
"""A disk's SMART health, temperature (``-1`` if unknown) and rpm (``0``)."""
|
||||
health, temperature, rpm = "unknown", -1, 0
|
||||
def _lsblk(self) -> list[dict[str, Any]]:
|
||||
"""The block devices lsblk lists; a failed or garbled read raises."""
|
||||
raw = self._send(_LSBLK)
|
||||
try:
|
||||
smart = self._sudo(_SMARTCTL.format(name=name), read_timeout=15)
|
||||
health = smart_health(smart)
|
||||
temperature = smart_temperature(smart)
|
||||
if disk_type == "hdd":
|
||||
rpm_m = re.search(r"Rotation Rate:\s+(\d+)\s+rpm", smart)
|
||||
if rpm_m:
|
||||
rpm = int(rpm_m.group(1))
|
||||
except Exception:
|
||||
logger.debug("%s: smartctl for %s: ignored", self.hostname, name, exc_info=True)
|
||||
return health, temperature, rpm
|
||||
devices = _json.loads(raw)["blockdevices"]
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
raise CommandErrorException(
|
||||
f"lsblk on {self.hostname} printed no device list: {raw[-300:]!r}"
|
||||
) from exc
|
||||
if not isinstance(devices, list):
|
||||
raise CommandErrorException(f"lsblk on {self.hostname}: blockdevices is no list")
|
||||
return devices
|
||||
|
||||
def _smart(self, name: str, disk_type: str) -> tuple[str, int, int]:
|
||||
"""A disk's SMART health, temperature (``-1`` if unknown) and rpm (``0``).
|
||||
|
||||
A smartctl call that failed (timeout, sudo refused, device not opened) is
|
||||
logged as a warning, so it is told apart from a disk without SMART; the
|
||||
disk stays in the inventory as ``"unknown"``.
|
||||
"""
|
||||
try:
|
||||
smart, status = self._sudo_status(
|
||||
_SMARTCTL.format(name=name), read_timeout=_SMARTCTL_TIMEOUT
|
||||
)
|
||||
except OSError as exc: # TimeoutError and the socket's own errors
|
||||
logger.warning("%s: smartctl for %s failed: %s", self.hostname, name, exc)
|
||||
return "unknown", -1, 0
|
||||
if status is not None and status & _SMARTCTL_CALL_FAILED:
|
||||
logger.warning(
|
||||
"%s: smartctl for %s failed (exit status %s): %s",
|
||||
self.hostname,
|
||||
name,
|
||||
status,
|
||||
smart[-300:],
|
||||
)
|
||||
return "unknown", -1, 0
|
||||
rpm = 0
|
||||
if disk_type == "hdd":
|
||||
rpm_m = re.search(r"Rotation Rate:\s+(\d+)\s+rpm", smart)
|
||||
if rpm_m:
|
||||
rpm = int(rpm_m.group(1))
|
||||
return smart_health(smart), smart_temperature(smart), rpm
|
||||
|
||||
def _md_members(self) -> dict[str, str]:
|
||||
"""The md array of each member device, from one read of ``/proc/mdstat``."""
|
||||
try:
|
||||
return md_members(self._send("cat /proc/mdstat 2>/dev/null"))
|
||||
except Exception:
|
||||
logger.debug("%s: /proc/mdstat not read: ignored", self.hostname, exc_info=True)
|
||||
return {}
|
||||
"""The md array of each member device, from one read of ``/proc/mdstat``.
|
||||
|
||||
A host without the md driver has no ``/proc/mdstat`` and no members; a
|
||||
failed read raises.
|
||||
"""
|
||||
return md_members(self._send("cat /proc/mdstat 2>/dev/null"))
|
||||
|
||||
# ── md RAID pools ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in new issue
Block a user