WindowsStorageMixin implements napalm-device-types' HostStorageMixin, so the host reports its storage and stays a host: - get_disks: Get-PhysicalDisk with medium, bus, Windows' health and the Storage Spaces pool a disk is in; a Storage Spaces virtual disk is no physical disk. - get_disk_smart: Get-StorageReliabilityCounter per disk (temperature, wear, power-on hours, uncorrected read and write errors). A counter that cannot be read is no counter, not an error; disks that report nothing are left out. - get_disk_pools: Storage Spaces' pools. - get_volumes: fixed volumes mounted at a drive letter or in a folder, with file system and health. A disk whose medium Windows cannot tell and whose counters are empty (a virtual disk, a RAID controller's logical disk) reads temperature -1 and health "unknown". Every script probes its cmdlets first. The fixtures are synthetic; the scripts are in harvest.py for the first real host.
356 lines
15 KiB
Python
356 lines
15 KiB
Python
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
|
|
|
|
:class:`WindowsStorageMixin` implements napalm-device-types'
|
|
:class:`~napalm_device_types.host_storage.HostStorageMixin` for the driver, which carries
|
|
each script across ``PsrpTransport.run``. A Windows host has disks; it is not a storage
|
|
device, so the getters come with no role and the driver stays ``windows``.
|
|
|
|
Everything is read from the Storage module's CIM classes, the same on every Windows
|
|
Server 2016+ and Windows 10/11, without installing anything:
|
|
|
|
- **Disks** are ``Get-PhysicalDisk``: model, serial, medium (``MediaType``), bus
|
|
(``BusType``; NVMe is a type of its own) and Windows' verdict (``HealthStatus``). A
|
|
Storage Spaces virtual disk (``BusType`` ``Spaces``) is built from other disks and is no
|
|
physical disk; its members are. Which pool a disk belongs to is
|
|
``Get-StoragePool -IsPrimordial $false`` with its member disks.
|
|
- **Drive health** is ``Get-StorageReliabilityCounter`` per disk: temperature, wear,
|
|
power-on hours, uncorrected read and write errors. It needs an administrator, and a
|
|
virtual disk often has none: a disk whose counter cannot be read has no counter, which
|
|
is "unknown", not an error. Windows writes ``0`` where a drive does not report a value,
|
|
so a zero temperature is none, and a disk whose counters are all empty reports nothing.
|
|
- **Health without a measurement is "unknown".** A disk whose medium Windows cannot tell
|
|
(``MediaType`` ``Unspecified``) and whose counters are empty is a virtual disk or a RAID
|
|
controller's logical disk; Windows calls it ``Healthy``, which says it is attached, not
|
|
that a drive is well. Its health reads ``unknown``. ``Warning`` and ``Unhealthy`` are
|
|
always passed on.
|
|
- **Pools** are Storage Spaces' ``Get-StoragePool -IsPrimordial $false``. Their size and
|
|
allocation are raw capacity: what is usable depends on each virtual disk's resiliency.
|
|
- **Volumes** are ``Get-Volume``'s fixed volumes, mounted at a drive letter or in a
|
|
folder (``Get-Partition``'s ``AccessPaths``). A volume mounted nowhere -- the EFI system
|
|
partition, the recovery partition -- is left out.
|
|
|
|
Each script asks ``Get-Command`` first, so a host without the Storage module answers "not
|
|
supported" (empty) rather than failing. Drive health is read with the disks, in one round
|
|
trip; ``get_disks`` and ``get_disk_smart`` each send it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from napalm_device_types.host_storage import DiskSmartDict, HostStorageMixin, HostVolumeDict
|
|
from napalm_device_types.models import DiskPoolDict, LogicalVolumeDict, PhysicalDiskDict
|
|
|
|
from napalm_windows._powershell import _as_list
|
|
|
|
_PS_DISKS = r"""
|
|
$ErrorActionPreference = 'Stop'
|
|
if (-not (Get-Command -Name Get-PhysicalDisk -ErrorAction SilentlyContinue)) {
|
|
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
|
|
return
|
|
}
|
|
$readCounters = [bool](
|
|
Get-Command -Name Get-StorageReliabilityCounter -ErrorAction SilentlyContinue
|
|
)
|
|
$pools = @{}
|
|
if (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue) {
|
|
try {
|
|
foreach ($pool in @(Get-StoragePool -IsPrimordial $false)) {
|
|
foreach ($member in @(Get-PhysicalDisk -StoragePool $pool)) {
|
|
$pools[[string]$member.UniqueId] = [string]$pool.FriendlyName
|
|
}
|
|
}
|
|
} catch { }
|
|
}
|
|
$disks = @(Get-PhysicalDisk | ForEach-Object {
|
|
$disk = $_
|
|
$counter = $null
|
|
if ($readCounters) {
|
|
try { $counter = $disk | Get-StorageReliabilityCounter } catch { $counter = $null }
|
|
}
|
|
[pscustomobject]@{
|
|
device_id = [string]$disk.DeviceId
|
|
unique_id = [string]$disk.UniqueId
|
|
name = [string]$disk.FriendlyName
|
|
model = [string]$disk.Model
|
|
vendor = [string]$disk.Manufacturer
|
|
serial = [string]$disk.SerialNumber
|
|
media_type = [string]$disk.MediaType
|
|
bus_type = [string]$disk.BusType
|
|
health = [string]$disk.HealthStatus
|
|
size = $disk.Size
|
|
spindle = $disk.SpindleSpeed
|
|
pool = $pools[[string]$disk.UniqueId]
|
|
counter = if ($counter) {
|
|
[pscustomobject]@{
|
|
temperature = $counter.Temperature
|
|
temperature_max = $counter.TemperatureMax
|
|
wear = $counter.Wear
|
|
power_on_hours = $counter.PowerOnHours
|
|
read_errors_uncorrected = $counter.ReadErrorsUncorrected
|
|
write_errors_uncorrected = $counter.WriteErrorsUncorrected
|
|
}
|
|
} else { $null }
|
|
}
|
|
})
|
|
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
|
supported = $true
|
|
counters = $readCounters
|
|
disks = $disks
|
|
})
|
|
"""
|
|
|
|
_PS_STORAGE_POOLS = r"""
|
|
$ErrorActionPreference = 'Stop'
|
|
if (-not (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue)) {
|
|
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
|
|
return
|
|
}
|
|
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
|
supported = $true
|
|
pools = @(Get-StoragePool -IsPrimordial $false | ForEach-Object {
|
|
$pool = $_
|
|
[pscustomobject]@{
|
|
name = [string]$pool.FriendlyName
|
|
health = [string]$pool.HealthStatus
|
|
operational = @($pool.OperationalStatus | ForEach-Object { [string]$_ })
|
|
size = $pool.Size
|
|
allocated = $pool.AllocatedSize
|
|
resiliency = [string]$pool.ResiliencySettingNameDefault
|
|
read_only = [bool]$pool.IsReadOnly
|
|
disks = @(Get-PhysicalDisk -StoragePool $pool | ForEach-Object {
|
|
[pscustomobject]@{
|
|
device_id = [string]$_.DeviceId
|
|
unique_id = [string]$_.UniqueId
|
|
}
|
|
})
|
|
}
|
|
})
|
|
})
|
|
"""
|
|
|
|
_PS_VOLUMES = r"""
|
|
$ErrorActionPreference = 'Stop'
|
|
if (-not (Get-Command -Name Get-Volume -ErrorAction SilentlyContinue)) {
|
|
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
|
|
return
|
|
}
|
|
$mounts = @{}
|
|
try {
|
|
foreach ($partition in @(Get-Partition)) {
|
|
$paths = @($partition.AccessPaths | Where-Object { $_ })
|
|
$folders = @($paths | Where-Object { $_ -notlike '\\?\*' })
|
|
foreach ($path in @($paths | Where-Object { $_ -like '\\?\Volume*' })) {
|
|
$mounts[$path] = $folders
|
|
}
|
|
}
|
|
} catch { }
|
|
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
|
supported = $true
|
|
volumes = @(Get-Volume | Where-Object { [string]$_.DriveType -eq 'Fixed' } | ForEach-Object {
|
|
$volume = $_
|
|
[pscustomobject]@{
|
|
letter = [string]$volume.DriveLetter
|
|
label = [string]$volume.FileSystemLabel
|
|
file_system = [string]$volume.FileSystem
|
|
size = $volume.Size
|
|
remaining = $volume.SizeRemaining
|
|
health = [string]$volume.HealthStatus
|
|
path = [string]$volume.Path
|
|
mounts = @($mounts[[string]$volume.Path])
|
|
}
|
|
})
|
|
})
|
|
"""
|
|
|
|
#: ``HealthStatus`` as the contract says it; anything else is "unknown".
|
|
_HEALTH = {"healthy": "healthy", "warning": "warning", "unhealthy": "failed"}
|
|
#: The same verdict in drive-health terms.
|
|
_DRIVE_HEALTH = {"healthy": "ok", "warning": "warning", "unhealthy": "failed"}
|
|
_MEDIA = {"hdd": "hdd", "ssd": "ssd", "scm": "ssd"}
|
|
_POOL_STATUS = {"healthy": "online", "warning": "degraded", "unhealthy": "faulted"}
|
|
_LEVELS = {"simple": "stripe", "mirror": "mirror", "parity": "parity"}
|
|
#: Buses of a disk built from other disks, not a drive.
|
|
_VIRTUAL_BUSES = frozenset({"spaces", "storage spaces"})
|
|
#: ``SpindleSpeed`` when Windows does not know it.
|
|
_UNKNOWN_SPEED = 0xFFFFFFFF
|
|
|
|
|
|
def _text(value: Any) -> str:
|
|
return str(value or "").strip()
|
|
|
|
|
|
def _number(value: Any) -> int | None:
|
|
"""A counter's value; ``None`` when the drive does not report it."""
|
|
return None if value is None else int(value)
|
|
|
|
|
|
def _positive(value: Any) -> int | None:
|
|
"""A value Windows writes as ``0`` when it has none (a temperature)."""
|
|
number = _number(value)
|
|
return number if number else None
|
|
|
|
|
|
def _slot(device_id: Any, unique_id: Any) -> str:
|
|
"""``PhysicalDisk<N>``, as ``Get-PhysicalDisk`` names a disk; its id when it has no number."""
|
|
number = _text(device_id)
|
|
return f"PhysicalDisk{number}" if number else _text(unique_id)
|
|
|
|
|
|
class _Disk:
|
|
"""One disk of ``_PS_DISKS``."""
|
|
|
|
def __init__(self, raw: dict[str, Any]) -> None:
|
|
self.raw = raw
|
|
self.slot = _slot(raw.get("device_id"), raw.get("unique_id"))
|
|
self.counter: dict[str, Any] = raw.get("counter") or {}
|
|
self.reports = any(value for value in self.counter.values())
|
|
bus = _text(raw.get("bus_type")).lower()
|
|
media = _MEDIA.get(_text(raw.get("media_type")).lower(), "unknown")
|
|
self.type = "nvme" if bus == "nvme" else media
|
|
self.is_physical = bus not in _VIRTUAL_BUSES
|
|
self.status = _text(raw.get("health")).lower()
|
|
|
|
def health(self) -> str:
|
|
verdict = _HEALTH.get(self.status, "unknown")
|
|
if verdict == "healthy" and self.type == "unknown" and not self.reports:
|
|
return "unknown"
|
|
return verdict
|
|
|
|
def disk(self) -> PhysicalDiskDict:
|
|
spindle = int(self.raw.get("spindle") or 0)
|
|
return {
|
|
"slot": self.slot,
|
|
"model": _text(self.raw.get("model") or self.raw.get("name")),
|
|
"serial": _text(self.raw.get("serial")),
|
|
"vendor": _text(self.raw.get("vendor")),
|
|
"type": self.type,
|
|
"size": int(self.raw.get("size") or 0),
|
|
"rpm": spindle if spindle != _UNKNOWN_SPEED else 0,
|
|
"temperature": _positive(self.counter.get("temperature")) or -1,
|
|
"health": self.health(),
|
|
"pool": _text(self.raw.get("pool")),
|
|
}
|
|
|
|
def smart(self) -> DiskSmartDict:
|
|
c = self.counter
|
|
return {
|
|
"model": _text(self.raw.get("model") or self.raw.get("name")),
|
|
"serial": _text(self.raw.get("serial")),
|
|
"type": self.type,
|
|
"size": int(self.raw.get("size") or 0),
|
|
"health": _DRIVE_HEALTH.get(self.status, "unknown"),
|
|
"wearout": None,
|
|
"temperature": _positive(c.get("temperature")),
|
|
# A spinning disk does not wear out by writes; its Wear is no reading.
|
|
"percentage_used": None if self.type == "hdd" else _number(c.get("wear")),
|
|
"available_spare": None,
|
|
"reallocated_sectors": None,
|
|
"power_on_hours": _number(c.get("power_on_hours")),
|
|
"temperature_max": _positive(c.get("temperature_max")),
|
|
"read_errors_uncorrected": _number(c.get("read_errors_uncorrected")),
|
|
"write_errors_uncorrected": _number(c.get("write_errors_uncorrected")),
|
|
}
|
|
|
|
|
|
def _pool(raw: dict[str, Any]) -> DiskPoolDict:
|
|
total, used = int(raw.get("size") or 0), int(raw.get("allocated") or 0)
|
|
resiliency = _text(raw.get("resiliency")).lower()
|
|
return {
|
|
"name": _text(raw.get("name")),
|
|
"type": "storage-spaces",
|
|
"level": _LEVELS.get(resiliency, resiliency or "unknown"),
|
|
"status": _POOL_STATUS.get(_text(raw.get("health")).lower(), "unknown"),
|
|
"total": total,
|
|
"used": used,
|
|
"available": max(total - used, 0),
|
|
"disks": [
|
|
_slot(d.get("device_id"), d.get("unique_id")) for d in _as_list(raw.get("disks"))
|
|
],
|
|
"auto_expand": False,
|
|
"dedup": False,
|
|
"compression": "off",
|
|
}
|
|
|
|
|
|
def _mount(raw: dict[str, Any]) -> tuple[str, str] | None:
|
|
"""The volume's key and mount point: its drive letter, else the first folder it is
|
|
mounted in; None when it is mounted nowhere."""
|
|
letter = _text(raw.get("letter")).split("\x00", 1)[0]
|
|
if letter:
|
|
return f"{letter}:", f"{letter}:\\"
|
|
folders = [_text(m) for m in _as_list(raw.get("mounts")) if _text(m)]
|
|
if not folders:
|
|
return None
|
|
return folders[0].rstrip("\\"), folders[0]
|
|
|
|
|
|
def _volume(raw: dict[str, Any], key: str, mountpoint: str) -> HostVolumeDict:
|
|
total, available = int(raw.get("size") or 0), int(raw.get("remaining") or 0)
|
|
return {
|
|
"name": _text(raw.get("label")) or key,
|
|
"pool": "",
|
|
"type": "filesystem",
|
|
"total": total,
|
|
"used": max(total - available, 0),
|
|
"available": available,
|
|
"mountpoint": mountpoint,
|
|
"compression": "",
|
|
"dedup": False,
|
|
"readonly": False,
|
|
"snapshots": 0,
|
|
"file_system": _text(raw.get("file_system")),
|
|
"health": _HEALTH.get(_text(raw.get("health")).lower(), "unknown"),
|
|
}
|
|
|
|
|
|
class WindowsStorageMixin(HostStorageMixin):
|
|
"""The Storage module's disks, pools, volumes and reliability counters."""
|
|
|
|
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
|
|
|
def _run_raw(self, script: str) -> str: ...
|
|
|
|
def _storage_read(self, script: str, what: str) -> dict[str, Any] | None:
|
|
"""The script's answer; None when the host has no Storage module.
|
|
|
|
:raises ValueError: when the reading came back empty -- it could not look.
|
|
"""
|
|
out = self._run_raw(script).strip()
|
|
raw = json.loads(out) if out else None
|
|
if not isinstance(raw, dict):
|
|
raise ValueError(f"the {what} reading came back empty")
|
|
return raw if raw.get("supported") else None
|
|
|
|
def _disks(self) -> list[_Disk]:
|
|
raw = self._storage_read(_PS_DISKS, "disk")
|
|
if raw is None:
|
|
return []
|
|
disks = (_Disk(d) for d in _as_list(raw.get("disks")))
|
|
return [d for d in disks if d.is_physical]
|
|
|
|
def get_disks(self) -> list[PhysicalDiskDict]:
|
|
"""``Get-PhysicalDisk`` with each disk's temperature; see the module."""
|
|
return [d.disk() for d in self._disks()]
|
|
|
|
def get_disk_smart(self) -> dict[str, DiskSmartDict]:
|
|
"""``Get-StorageReliabilityCounter`` per disk; disks that report nothing are left out."""
|
|
return {d.slot: d.smart() for d in self._disks() if d.reports}
|
|
|
|
def get_disk_pools(self) -> dict[str, DiskPoolDict]:
|
|
"""Storage Spaces' pools; ``{}`` on a host without any."""
|
|
raw = self._storage_read(_PS_STORAGE_POOLS, "storage pool")
|
|
pools = [_pool(p) for p in _as_list((raw or {}).get("pools"))]
|
|
return {p["name"]: p for p in pools}
|
|
|
|
def get_volumes(self) -> dict[str, LogicalVolumeDict]:
|
|
"""``Get-Volume``'s fixed volumes that are mounted somewhere, keyed by where."""
|
|
raw = self._storage_read(_PS_VOLUMES, "volume")
|
|
volumes: dict[str, LogicalVolumeDict] = {}
|
|
for entry in _as_list((raw or {}).get("volumes")):
|
|
mount = _mount(entry)
|
|
if mount is not None:
|
|
volumes[mount[0]] = _volume(entry, *mount)
|
|
return volumes
|