Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89a52db1a5 | ||
|
|
21a21383ff | ||
|
|
84f6a3c3e3 |
No files matched your search
+17
-11
@@ -7,17 +7,23 @@ All notable changes to this driver. The format follows
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Disks, pools, volumes and drive health without smartctl (NetOrk/netork#2896), through
|
||||
napalm-device-types' `HostStorageMixin`, so the host stays a host. `get_disks` reads
|
||||
`Get-PhysicalDisk` (model, serial, medium, NVMe, Windows' health, the Storage Spaces
|
||||
pool a disk is in); `get_disk_smart` reads `Get-StorageReliabilityCounter` per disk
|
||||
(temperature, wear, power-on hours, uncorrected read and write errors);
|
||||
`get_disk_pools` reads Storage Spaces' pools; `get_volumes` the fixed volumes mounted at
|
||||
a drive letter or in a folder, with file system and health. A disk whose counter cannot
|
||||
be read -- the cmdlet needs an administrator, and virtual disks often have none -- has
|
||||
no drive health rather than an error; a virtual disk or a RAID controller's logical
|
||||
disk reads temperature -1 and health "unknown" instead of zeros and a "healthy" nobody
|
||||
measured. A Storage Spaces virtual disk is not listed as a physical disk.
|
||||
- What the event log recorded that says something is wrong with the host
|
||||
(NetOrk/netork#2897): `get_host_events(since=None)`, napalm-device-types'
|
||||
`HostEventsMixin`. Unexpected shutdowns (Kernel-Power 41, EventLog 6008), bugchecks
|
||||
with their stop code (1001), fatal and corrected hardware errors (WHEA-Logger 18, 19,
|
||||
47), disk and file system errors (disk 7 and 153, Ntfs 55), crashing programs
|
||||
(Application Error 1000) and services that ended unexpectedly (Service Control
|
||||
Manager 7031, 7034), over the last seven days by default, in one script of three
|
||||
queries bounded by time and count. An empty log is no events, not an error
|
||||
(`NoMatchingEventsFound` is caught); a query that fails names its kinds `unread`.
|
||||
- The event channels as the host's log sources: `get_log_sources()` lists every channel
|
||||
that is switched on and holds records as a source of kind `eventlog`, named by its
|
||||
channel, with its `.evtx` file, size and last write (`Get-WinEvent -ListLog *`).
|
||||
Analytic and debug channels are left out.
|
||||
- `get_services()` says how each service's last run ended (`result`, `exit_code`, from
|
||||
`Win32_Service.ExitCode` and `ServiceSpecificExitCode`), whether a trigger starts it
|
||||
(`trigger_start`) and the account it runs as (`account`), so that an automatic service
|
||||
that died is told from one stopped on purpose. It moves into `WindowsServicesMixin`.
|
||||
- Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and
|
||||
`shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin`
|
||||
run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with
|
||||
|
||||
@@ -36,14 +36,15 @@ handshake once.
|
||||
| `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) |
|
||||
| `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) |
|
||||
| `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) |
|
||||
| `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` |
|
||||
| `get_services` / `manage_service` | `Win32_Service` (with `ExitCode`, `StartName`) and the services' `TriggerInfo` registry keys, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType`. See *Services* |
|
||||
| `reboot_host` / `shutdown_host` | `Restart-Computer`, `Stop-Computer`, neither with `-Force`: programs are asked to close, and Windows refuses while other users are logged on. A connection the host drops before answering counts as accepted |
|
||||
| `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) |
|
||||
| `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones |
|
||||
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
|
||||
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
|
||||
| `get_host_events` | `Get-WinEvent -FilterXPath`, three bounded queries over the System and Application logs. See *Host events* |
|
||||
| `get_log_sources` | `Get-WinEvent -ListLog *`: every event channel switched on and holding records, as kind `eventlog` |
|
||||
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
|
||||
| `get_disks` / `get_disk_smart` / `get_disk_pools` / `get_volumes` | `Get-PhysicalDisk`, `Get-StorageReliabilityCounter`, `Get-StoragePool -IsPrimordial $false`, `Get-Volume` + `Get-Partition`; no smartctl. See *Storage* |
|
||||
|
||||
`running_kernel` carries the full build including the update revision
|
||||
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
|
||||
@@ -98,32 +99,37 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
|
||||
zone with summer time switched off reads as `None`; writing the zone switches it
|
||||
back on.
|
||||
|
||||
### Storage
|
||||
### Services
|
||||
|
||||
napalm-device-types' `HostStorageMixin` (NetOrk/netork#2896): the host's storage without
|
||||
the storage role, so the driver stays a host. Nothing is installed; everything comes from
|
||||
the Storage module's CIM classes.
|
||||
How a service's last run ended is `Win32_Service.ExitCode`, said in systemd's words
|
||||
(napalm-device-types' `ServiceDict.result`): `0` is `success`, `1077` (never started
|
||||
since boot: a demand-start service, or a delayed one in the minutes after boot) is no
|
||||
result, `1066` is `exit-code` with the service's own `ServiceSpecificExitCode`, any
|
||||
other code `exit-code` with that code (`1067`: the process ended without being
|
||||
stopped). Both codes leave the host as `[int64]`: they are UInt32, and an HRESULT
|
||||
would not fit `[int]`. `trigger_start` is a `TriggerInfo` key under the service, read
|
||||
once for all of them; `account` is `StartName`.
|
||||
|
||||
* **Disks** are `Get-PhysicalDisk` (`PhysicalDisk<N>` by `DeviceId`): model, serial,
|
||||
medium, bus (NVMe is its own type), Windows' `HealthStatus` (`Healthy`, `Warning`,
|
||||
`Unhealthy` -> `healthy`, `warning`, `failed`) and, for disks in a Storage Spaces pool,
|
||||
the pool. A Storage Spaces virtual disk is no physical disk and is not listed.
|
||||
* **Drive health** (`get_disk_smart`) is `Get-StorageReliabilityCounter` per disk:
|
||||
temperature and its highest, wear (`percentage_used`, not for spinning disks), power-on
|
||||
hours, uncorrected read and write errors. It needs an administrator; a disk whose
|
||||
counter cannot be read, or whose counters are all empty, has no drive health and is
|
||||
left out. Windows writes `0` for a temperature it does not have, which reads as none.
|
||||
* **Unknown is not healthy.** 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`: Windows calls it `Healthy`, which only says it is attached.
|
||||
`Warning` and `Unhealthy` are always passed on.
|
||||
* **Pools** are Storage Spaces (`storage-spaces`; `Simple`, `Mirror`, `Parity` ->
|
||||
`stripe`, `mirror`, `parity`). Size and allocation are raw capacity.
|
||||
* **Volumes** are the fixed volumes mounted at a drive letter (`C:`) or in a folder
|
||||
(`C:\Logs`), with file system and health; the EFI and recovery partitions are mounted
|
||||
nowhere and left out.
|
||||
### Host events
|
||||
|
||||
A host without the Storage module reads as having none; an empty answer raises.
|
||||
napalm-device-types' `HostEventsMixin`: what the event log recorded that says
|
||||
something is wrong with the host, over the last seven days unless the caller names a
|
||||
start. One script, three queries, each an XPath filter from the start on, newest
|
||||
first and bounded by count:
|
||||
|
||||
| Query | Events | Bound |
|
||||
|---|---|---|
|
||||
| System, with messages | Kernel-Power 41 and EventLog 6008 (unexpected shutdown; 41's `BugcheckCode` as the stop code), WER-SystemErrorReporting 1001 (bugcheck, its stop code), WHEA-Logger 18 (fatal hardware error), disk 7 (bad block), Ntfs 55 (corruption, its volume) | 100 |
|
||||
| System, without messages | WHEA-Logger 19 and 47 (corrected hardware errors), disk 153 (retried I/O, its disk), Service Control Manager 7031 and 7034 (a service that ended unexpectedly, its display name) | 500 |
|
||||
| Application, without messages | Application Error 1000 (a program that crashed, its path) | 200 |
|
||||
|
||||
`Get-WinEvent` throws `NoMatchingEventsFound` when nothing matches; each query
|
||||
catches it as no events, and any other failure costs only that query, whose kinds the
|
||||
reading names `unread`. A query that returned its bound names its kinds `capped`.
|
||||
What an event is about comes from its properties, never from its message, which is in
|
||||
the host's language; messages are read only for the rare events (Windows formats them
|
||||
slowly) and cut to 300 characters. Which of them is worth a warning is the
|
||||
application's to say.
|
||||
|
||||
Not yet: packages, Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""The event channels as the host's log sources (NetOrk/netork#2897).
|
||||
|
||||
:class:`WindowsLogSourcesMixin` gives the driver ``get_log_sources`` in napalm-device-types'
|
||||
shape (``LogSourcesDict``). A Windows host keeps no journal and its programs hold no log
|
||||
files a reader could name: its logs are its event channels, each a source of kind
|
||||
``eventlog`` named by its channel -- the name CrowdSec (``event_channel``) and Wazuh
|
||||
(``eventchannel``) read it by -- with its ``.evtx`` file as ``path``.
|
||||
|
||||
One script, ``Get-WinEvent -ListLog *``: every channel that is switched on and holds
|
||||
records, with its file (``%SystemRoot%`` expanded), size, last write and type. A channel
|
||||
the account may not open is skipped, not the reading. Analytic and debug channels are
|
||||
trace sessions written to ``.etl`` files, which a log reader cannot follow, and are left
|
||||
out. WinRM needs an administrator, who may open every other channel, the Security log
|
||||
included, so the reading is ``attributed``. Where the logs go beyond the host (Windows
|
||||
Event Forwarding, an agent) is not read: ``forwarding`` is None.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import LogSourceDict, LogSourcesDict, eventlog_source
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_PS_EVENT_CHANNELS = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-WinEvent -ListLog * -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.IsEnabled -and $_.RecordCount } |
|
||||
ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
channel = $_.LogName
|
||||
path = [Environment]::ExpandEnvironmentVariables([string]$_.LogFilePath)
|
||||
size = $_.FileSize
|
||||
modified = if ($_.LastWriteTime) {
|
||||
([DateTimeOffset]$_.LastWriteTime).ToUnixTimeSeconds()
|
||||
} else { $null }
|
||||
records = $_.RecordCount
|
||||
type = [string]$_.LogType
|
||||
}
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
#: Trace sessions, not logs: written to .etl files a reader cannot follow.
|
||||
_TRACE_TYPES = frozenset({"analytic", "debug"})
|
||||
|
||||
|
||||
def _is_log(raw: dict[str, Any]) -> bool:
|
||||
return (
|
||||
bool(raw.get("channel"))
|
||||
and int(raw.get("records") or 0) > 0
|
||||
and str(raw.get("type") or "").lower() not in _TRACE_TYPES
|
||||
)
|
||||
|
||||
|
||||
def _source(raw: dict[str, Any]) -> LogSourceDict:
|
||||
size, modified = raw.get("size"), raw.get("modified")
|
||||
return eventlog_source(
|
||||
str(raw["channel"]),
|
||||
str(raw["path"]) if raw.get("path") else None,
|
||||
None if size is None else int(size),
|
||||
None if modified is None else float(modified),
|
||||
)
|
||||
|
||||
|
||||
class WindowsLogSourcesMixin:
|
||||
"""``get_log_sources``: the host's event channels; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_log_sources(self) -> LogSourcesDict:
|
||||
"""Every event channel that is switched on and holds records, sorted by name.
|
||||
|
||||
* attributed (bool) - always True: an administrator opens every channel
|
||||
* journald (bool) - always False: Windows keeps event channels, not a journal
|
||||
* sources (list) - one ``eventlog`` source per channel
|
||||
* forwarding - None: where the logs go beyond the host is not read
|
||||
"""
|
||||
channels = [c for c in _as_list(self._run_ps(_PS_EVENT_CHANNELS)) if _is_log(c)]
|
||||
sources = sorted((_source(c) for c in channels), key=lambda s: s.get("channel", ""))
|
||||
return {"attributed": True, "journald": False, "sources": sources, "forwarding": None}
|
||||
@@ -0,0 +1,254 @@
|
||||
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
|
||||
|
||||
:class:`WindowsHostEventsMixin` implements napalm-device-types'
|
||||
:class:`~napalm_device_types.host_events.HostEventsMixin` for the driver, which carries
|
||||
the script across ``PsrpTransport.run``.
|
||||
|
||||
**One script, three queries**, each an XPath filter over a fixed set of providers and
|
||||
event IDs, from the reading's start (``TimeCreated[@SystemTime>=…]``), newest first and
|
||||
bounded by count:
|
||||
|
||||
* *rare*, the System log, with each event's message: Kernel-Power 41 and EventLog 6008
|
||||
(an unexpected shutdown; 41's first property is the bugcheck code, 0 for a power loss),
|
||||
WER-SystemErrorReporting 1001 (a bugcheck, its stop code first), WHEA-Logger 18 (a
|
||||
fatal hardware error), disk 7 (a bad block) and Ntfs 55 (a corruption);
|
||||
* *frequent*, the System log without messages, which Windows formats slowly: WHEA-Logger
|
||||
19 and 47 (corrected hardware errors), disk 153 (a retried I/O) and Service Control
|
||||
Manager 7031 and 7034 (a service that ended unexpectedly);
|
||||
* *apps*, the Application log without messages: Application Error 1000 (a program that
|
||||
crashed, its path the eleventh property).
|
||||
|
||||
``Get-WinEvent`` throws ``NoMatchingEventsFound`` when nothing matches, and under
|
||||
``$ErrorActionPreference = 'Stop'`` that would fail the whole reading: each query
|
||||
catches it as no events. Any other failure costs only that query, whose kinds the
|
||||
reading names ``unread``; a query that returned its bound names its kinds ``capped``.
|
||||
|
||||
**What an event is about** is taken from its properties, which do not depend on the
|
||||
host's language, never from its message, which does: the stop code, the disk or volume,
|
||||
the program's path (its name on a Windows that records no path), the service's display
|
||||
name. The message is kept as the host wrote it, cut short.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import HOST_EVENT_KINDS, HostEventDict, HostEventsDict, HostEventsMixin
|
||||
from napalm_device_types import host_event as _event
|
||||
from napalm_device_types.host_events import (
|
||||
APP_CRASH,
|
||||
DISK_ERROR,
|
||||
HARDWARE_ERROR_CORRECTED,
|
||||
HARDWARE_ERROR_FATAL,
|
||||
HOST_EVENT_MESSAGE_CHARS,
|
||||
HOST_EVENT_WINDOW_DAYS,
|
||||
SERVICE_CRASH,
|
||||
SYSTEM_CRASH,
|
||||
UNEXPECTED_SHUTDOWN,
|
||||
)
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_KERNEL_POWER = "Microsoft-Windows-Kernel-Power"
|
||||
_BUGCHECK = "Microsoft-Windows-WER-SystemErrorReporting"
|
||||
_WHEA = "Microsoft-Windows-WHEA-Logger"
|
||||
_SCM = "Service Control Manager"
|
||||
_APP_ERROR = "Application Error"
|
||||
|
||||
|
||||
def _bugcheck(props: list[str]) -> str | None:
|
||||
"""Kernel-Power 41's ``BugcheckCode``, a decimal number, as a stop code; 0 is none."""
|
||||
word = props[0].strip() if props else ""
|
||||
return f"0x{int(word):08x}" if word.isdigit() and int(word) else None
|
||||
|
||||
|
||||
def _stop_code(props: list[str]) -> str | None:
|
||||
"""1001's first property: ``0x0000009f (0x…, 0x…, 0x…, 0x…)``."""
|
||||
word = props[0].split(maxsplit=1)[0] if props and props[0].strip() else ""
|
||||
return word or None
|
||||
|
||||
|
||||
def _first(props: list[str]) -> str | None:
|
||||
return props[0] if props else None
|
||||
|
||||
|
||||
def _program(props: list[str]) -> str | None:
|
||||
"""Application Error 1000: its path where the host records one, else its name."""
|
||||
path = props[10] if len(props) > 10 else ""
|
||||
return path.strip() or _first(props)
|
||||
|
||||
|
||||
def _none(props: list[str]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
_Subject = Callable[[list[str]], str | None]
|
||||
|
||||
#: (provider, event ID) -> the kind and what the event is about.
|
||||
_EVENTS: dict[tuple[str, int], tuple[str, _Subject]] = {
|
||||
(_KERNEL_POWER, 41): (UNEXPECTED_SHUTDOWN, _bugcheck),
|
||||
("EventLog", 6008): (UNEXPECTED_SHUTDOWN, _none),
|
||||
(_BUGCHECK, 1001): (SYSTEM_CRASH, _stop_code),
|
||||
(_WHEA, 18): (HARDWARE_ERROR_FATAL, _none),
|
||||
(_WHEA, 19): (HARDWARE_ERROR_CORRECTED, _none),
|
||||
(_WHEA, 47): (HARDWARE_ERROR_CORRECTED, _none),
|
||||
("disk", 7): (DISK_ERROR, _first),
|
||||
("disk", 153): (DISK_ERROR, _first),
|
||||
("Microsoft-Windows-Ntfs", 55): (DISK_ERROR, _first),
|
||||
("Ntfs", 55): (DISK_ERROR, _first),
|
||||
(_SCM, 7031): (SERVICE_CRASH, _first),
|
||||
(_SCM, 7034): (SERVICE_CRASH, _first),
|
||||
(_APP_ERROR, 1000): (APP_CRASH, _program),
|
||||
}
|
||||
|
||||
#: Each query's log, its events, its bound and whether it reads their messages.
|
||||
_QUERIES: dict[str, tuple[str, tuple[tuple[str, int], ...], int, bool]] = {
|
||||
"rare": (
|
||||
"System",
|
||||
(
|
||||
(_KERNEL_POWER, 41),
|
||||
("EventLog", 6008),
|
||||
(_BUGCHECK, 1001),
|
||||
(_WHEA, 18),
|
||||
("disk", 7),
|
||||
("Microsoft-Windows-Ntfs", 55),
|
||||
("Ntfs", 55),
|
||||
),
|
||||
100,
|
||||
True,
|
||||
),
|
||||
"frequent": (
|
||||
"System",
|
||||
((_WHEA, 19), (_WHEA, 47), ("disk", 153), (_SCM, 7031), (_SCM, 7034)),
|
||||
500,
|
||||
False,
|
||||
),
|
||||
"apps": ("Application", ((_APP_ERROR, 1000),), 200, False),
|
||||
}
|
||||
|
||||
#: The kinds each query reads, in the order of HOST_EVENT_KINDS.
|
||||
_PART_KINDS: dict[str, tuple[str, ...]] = {
|
||||
part: tuple(k for k in HOST_EVENT_KINDS if k in {_EVENTS[e][0] for e in events})
|
||||
for part, (_log, events, _max, _message) in _QUERIES.items()
|
||||
}
|
||||
|
||||
# Q runs one query: its events with their properties as strings, or why not.
|
||||
# $_ inside catch is the error; NoMatchingEventsFound is an empty log, not a failure.
|
||||
_PS_QUERY = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Q($log, $xpath, $max, $withMessage) {{
|
||||
try {{
|
||||
$rows = @(Get-WinEvent -LogName $log -FilterXPath $xpath -MaxEvents $max | ForEach-Object {{
|
||||
$m = $null
|
||||
if ($withMessage) {{
|
||||
try {{ $m = [string]$_.Message }} catch {{ $m = $null }}
|
||||
if ($m.Length -gt {HOST_EVENT_MESSAGE_CHARS}) {{
|
||||
$m = $m.Substring(0, {HOST_EVENT_MESSAGE_CHARS})
|
||||
}}
|
||||
}}
|
||||
[pscustomobject]@{{
|
||||
provider = $_.ProviderName
|
||||
id = [int]$_.Id
|
||||
time = ([DateTimeOffset]$_.TimeCreated).ToUnixTimeSeconds()
|
||||
props = @($_.Properties | Select-Object -First 11 |
|
||||
ForEach-Object {{ [string]$_.Value }})
|
||||
message = $m
|
||||
}}
|
||||
}})
|
||||
[pscustomobject]@{{ ok = $true; capped = ($rows.Count -ge $max); events = $rows }}
|
||||
}} catch {{
|
||||
if ([string]$_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{
|
||||
[pscustomobject]@{{ ok = $true; capped = $false; events = @() }}
|
||||
}} else {{
|
||||
[pscustomobject]@{{
|
||||
ok = $false; capped = $false; events = @(); error = [string]$_.Exception.Message
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def _xpath(events: tuple[tuple[str, int], ...], since: str) -> str:
|
||||
which = " or ".join(f"(Provider[@Name='{p}'] and EventID={i})" for p, i in events)
|
||||
return f"*[System[TimeCreated[@SystemTime>='{since}'] and ({which})]]"
|
||||
|
||||
|
||||
def host_events_script(since: float) -> str:
|
||||
"""The reading's script, from *since* (unix seconds) on."""
|
||||
start = datetime.fromtimestamp(since, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
||||
lines = [_PS_QUERY]
|
||||
parts = []
|
||||
for part, (log, events, bound, message) in _QUERIES.items():
|
||||
lines.append(f'${part} = "{_xpath(events, start)}"')
|
||||
parts.append(f" {part} = (Q '{log}' ${part} {bound} ${str(message).lower()})")
|
||||
lines.append("[pscustomobject]@{ parts = [pscustomobject]@{")
|
||||
lines.extend(parts)
|
||||
lines.append("} } | ConvertTo-Json -Compress -Depth 6")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _parse_event(raw: dict[str, Any], source_log: str) -> HostEventDict | None:
|
||||
known = _EVENTS.get((str(raw.get("provider") or ""), int(raw.get("id") or 0)))
|
||||
if known is None:
|
||||
return None
|
||||
kind, subject = known
|
||||
props = [str(p) for p in _as_list(raw.get("props"))]
|
||||
source = f"{source_log}: {raw.get('provider')} {raw.get('id')}"
|
||||
return _event(kind, float(raw.get("time") or 0), source, subject(props), raw.get("message"))
|
||||
|
||||
|
||||
def _part(answer: Any, log: str) -> list[HostEventDict] | None:
|
||||
"""One query's events; None when it was not read."""
|
||||
if not isinstance(answer, dict) or not answer.get("ok"):
|
||||
return None
|
||||
found = (_parse_event(e, log) for e in _as_list(answer.get("events")))
|
||||
return [e for e in found if e is not None]
|
||||
|
||||
|
||||
def _in_order(kinds: set[str]) -> list[str]:
|
||||
return [k for k in HOST_EVENT_KINDS if k in kinds]
|
||||
|
||||
|
||||
def _reading(raw: Any, since: float) -> HostEventsDict:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("parts"), dict):
|
||||
raise ValueError("the host events reading came back without a report")
|
||||
events: list[HostEventDict] = []
|
||||
capped: set[str] = set()
|
||||
unread: set[str] = set()
|
||||
for part, (log, _events, _bound, _message) in _QUERIES.items():
|
||||
answer = raw["parts"].get(part)
|
||||
found = _part(answer, log)
|
||||
if found is None:
|
||||
unread.update(_PART_KINDS[part])
|
||||
continue
|
||||
if answer.get("capped"):
|
||||
capped.update(_PART_KINDS[part])
|
||||
events.extend(found)
|
||||
events.sort(key=lambda e: e["time"], reverse=True)
|
||||
return {
|
||||
"since": datetime.fromtimestamp(since, UTC).isoformat(),
|
||||
"events": events,
|
||||
"capped": _in_order(capped),
|
||||
"unread": _in_order(unread),
|
||||
}
|
||||
|
||||
|
||||
class WindowsHostEventsMixin(HostEventsMixin):
|
||||
"""The event log's warnings-worthy events; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_host_events(self, since: float | None = None) -> HostEventsDict:
|
||||
"""The events of ``HOST_EVENT_KINDS`` since *since* (unix seconds), by default
|
||||
over the last ``HOST_EVENT_WINDOW_DAYS`` days; one round trip, see the module.
|
||||
|
||||
:raises ValueError: when the reading came back without a report.
|
||||
"""
|
||||
start = time.time() - HOST_EVENT_WINDOW_DAYS * 86400 if since is None else since
|
||||
return _reading(self._run_ps(host_events_script(start)), start)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""The host's services, and how each one's last run ended (NetOrk/netork#2897).
|
||||
|
||||
:class:`WindowsServicesMixin` reads ``get_services`` for the driver, which carries
|
||||
the script across ``PsrpTransport.run``.
|
||||
|
||||
One script: every ``Win32_Service`` with its state, start mode and process, the
|
||||
account it runs as (``StartName``) and the code its last run ended with
|
||||
(``ExitCode``). Both exit codes are UInt32 and leave the host as ``[int64]``, since
|
||||
``[int]`` would throw on an HRESULT and fail the reading. Which services a trigger
|
||||
starts (a device arriving, a network change, a request) is one registry read for all
|
||||
of them: the ``TriggerInfo`` keys under ``HKLM:\\SYSTEM\\CurrentControlSet\\Services``.
|
||||
|
||||
**How the last run ended** is said in systemd's words (napalm-device-types'
|
||||
``ServiceDict.result``), so that one rule reads it for every host:
|
||||
|
||||
* ``0`` is ``success``: running, or stopped on purpose.
|
||||
* ``1077`` (``ERROR_SERVICE_NEVER_STARTED``) is no result: not started since the
|
||||
host booted -- a demand-start service, or a delayed one in the minutes after boot.
|
||||
* ``1066`` (``ERROR_SERVICE_SPECIFIC_ERROR``) is ``exit-code`` with the service's own
|
||||
code, ``ServiceSpecificExitCode``.
|
||||
* Any other code is ``exit-code`` with that code: ``1067`` is a process that ended
|
||||
without being stopped.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_PS_SERVICES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$triggered = @{}
|
||||
$keys = 'HKLM:\SYSTEM\CurrentControlSet\Services\*\TriggerInfo'
|
||||
Get-Item -Path $keys -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { $triggered[(Split-Path -Path $_.PSParentPath -Leaf)] = $true }
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
name = $_.Name
|
||||
state = [string]$_.State
|
||||
start_mode = [string]$_.StartMode
|
||||
pid = [int]$_.ProcessId
|
||||
exit_code = [int64]$_.ExitCode
|
||||
service_code = [int64]$_.ServiceSpecificExitCode
|
||||
account = $_.StartName
|
||||
trigger_start = [bool]$triggered[$_.Name]
|
||||
}
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
_ENABLED_START_MODES = {"auto", "boot", "system"}
|
||||
#: ``ERROR_SERVICE_NEVER_STARTED``: no attempt to start it since the host booted.
|
||||
_NEVER_STARTED = 1077
|
||||
#: ``ERROR_SERVICE_SPECIFIC_ERROR``: the code is the service's own.
|
||||
_SERVICE_SPECIFIC = 1066
|
||||
|
||||
|
||||
def _result(raw: dict[str, Any]) -> tuple[str | None, int | None]:
|
||||
"""How the last run ended, and its code where that was not success."""
|
||||
code = raw.get("exit_code")
|
||||
if code is None or int(code) == _NEVER_STARTED:
|
||||
return None, None
|
||||
if int(code) == 0:
|
||||
return SERVICE_RESULT_SUCCESS, None
|
||||
if int(code) == _SERVICE_SPECIFIC and raw.get("service_code"):
|
||||
return SERVICE_RESULT_EXIT_CODE, int(raw["service_code"])
|
||||
return SERVICE_RESULT_EXIT_CODE, int(code)
|
||||
|
||||
|
||||
def _service(raw: dict[str, Any]) -> ServiceDict:
|
||||
running = str(raw.get("state") or "").lower() == "running"
|
||||
result, exit_code = _result(raw)
|
||||
return {
|
||||
"name": str(raw["name"]),
|
||||
"running": running,
|
||||
"enabled": str(raw.get("start_mode") or "").lower() in _ENABLED_START_MODES,
|
||||
"pid": int(raw.get("pid") or 0) if running else 0,
|
||||
"result": result,
|
||||
"exit_code": exit_code,
|
||||
"trigger_start": bool(raw.get("trigger_start")),
|
||||
"account": str(raw["account"]) if raw.get("account") else None,
|
||||
}
|
||||
|
||||
|
||||
class WindowsServicesMixin:
|
||||
"""``get_services`` from ``Win32_Service``; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_services(self) -> list[ServiceDict]:
|
||||
"""Every service with whether it runs, starts at boot, and how its last run ended."""
|
||||
return [_service(s) for s in _as_list(self._run_ps(_PS_SERVICES))]
|
||||
@@ -1,355 +0,0 @@
|
||||
"""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
|
||||
+12
-32
@@ -24,11 +24,13 @@ from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.event_channels import WindowsLogSourcesMixin
|
||||
from napalm_windows.host_events import WindowsHostEventsMixin
|
||||
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
|
||||
from napalm_windows.storage import WindowsStorageMixin
|
||||
from napalm_windows.services import WindowsServicesMixin
|
||||
from napalm_windows.time_sync import WindowsTimeSyncMixin
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
|
||||
@@ -124,20 +126,6 @@ ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
)
|
||||
"""
|
||||
|
||||
_PS_SERVICES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
name = $_.Name
|
||||
state = [string]$_.State
|
||||
start_mode = [string]$_.StartMode
|
||||
pid = [int]$_.ProcessId
|
||||
}
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
# Every listening TCP and bound UDP socket, the processes holding them and the
|
||||
# services those processes run. Sockets owned by http.sys (WinRM, IIS) belong to
|
||||
# the System process; a shared svchost runs several services in one process.
|
||||
@@ -202,7 +190,6 @@ _ROUTE_PROTOCOLS = {
|
||||
"rip": "rip",
|
||||
}
|
||||
|
||||
_ENABLED_START_MODES = {"auto", "boot", "system"}
|
||||
_DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
|
||||
|
||||
|
||||
@@ -262,7 +249,14 @@ def _is_noise_route(destination: str) -> bool:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsStorageMixin, OSDriver):
|
||||
class WindowsDriver(
|
||||
WindowsScheduledJobsMixin,
|
||||
WindowsTimeSyncMixin,
|
||||
WindowsServicesMixin,
|
||||
WindowsHostEventsMixin,
|
||||
WindowsLogSourcesMixin,
|
||||
OSDriver,
|
||||
):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
``optional_args``:
|
||||
@@ -490,20 +484,6 @@ class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsStor
|
||||
# Services
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_services(self) -> list[ServiceDict]:
|
||||
services: list[ServiceDict] = []
|
||||
for s in _as_list(self._run_ps(_PS_SERVICES)):
|
||||
running = (s.get("state") or "").lower() == "running"
|
||||
services.append(
|
||||
{
|
||||
"name": s["name"],
|
||||
"running": running,
|
||||
"enabled": (s.get("start_mode") or "").lower() in _ENABLED_START_MODES,
|
||||
"pid": int(s.get("pid") or 0) if running else 0,
|
||||
}
|
||||
)
|
||||
return services
|
||||
|
||||
def get_listening_sockets(self) -> ListeningSocketsDict:
|
||||
"""Every listening TCP and bound UDP socket, with the process and the
|
||||
Windows service behind it (``Get-NetTCPConnection``, ``Get-NetUDPEndpoint``,
|
||||
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
{
|
||||
"supported": true,
|
||||
"counters": true,
|
||||
"disks": [
|
||||
{
|
||||
"device_id": "0",
|
||||
"unique_id": "eui.0025385A11B22C33",
|
||||
"name": "Samsung SSD 980 PRO 1TB",
|
||||
"model": "Samsung SSD 980 PRO 1TB",
|
||||
"vendor": "",
|
||||
"serial": "0025_385A_11B2_2C33.",
|
||||
"media_type": "SSD",
|
||||
"bus_type": "NVMe",
|
||||
"health": "Healthy",
|
||||
"size": 1000204886016,
|
||||
"spindle": 0,
|
||||
"pool": null,
|
||||
"counter": {
|
||||
"temperature": 41,
|
||||
"temperature_max": 68,
|
||||
"wear": 3,
|
||||
"power_on_hours": 5120,
|
||||
"read_errors_uncorrected": 0,
|
||||
"write_errors_uncorrected": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"device_id": "1",
|
||||
"unique_id": "50014EE2B1C2D3E4",
|
||||
"name": "WDC WD40EFRX-68N32N0",
|
||||
"model": "WDC WD40EFRX-68N32N0",
|
||||
"vendor": "",
|
||||
"serial": " WD-WCC7K1ABCDEF",
|
||||
"media_type": "HDD",
|
||||
"bus_type": "SATA",
|
||||
"health": "Warning",
|
||||
"size": 4000787030016,
|
||||
"spindle": 5400,
|
||||
"pool": "Pool1",
|
||||
"counter": {
|
||||
"temperature": 36,
|
||||
"temperature_max": 51,
|
||||
"wear": 0,
|
||||
"power_on_hours": 31012,
|
||||
"read_errors_uncorrected": 12,
|
||||
"write_errors_uncorrected": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"device_id": "3",
|
||||
"unique_id": "50014EE2B1C2D3F5",
|
||||
"name": "WDC WD40EFRX-68N32N0",
|
||||
"model": "WDC WD40EFRX-68N32N0",
|
||||
"vendor": "",
|
||||
"serial": "WD-WCC7K1ABCDF0",
|
||||
"media_type": "HDD",
|
||||
"bus_type": "SATA",
|
||||
"health": "Healthy",
|
||||
"size": 4000787030016,
|
||||
"spindle": 4294967295,
|
||||
"pool": "Pool1",
|
||||
"counter": {
|
||||
"temperature": 0,
|
||||
"temperature_max": null,
|
||||
"wear": 0,
|
||||
"power_on_hours": 30990,
|
||||
"read_errors_uncorrected": null,
|
||||
"write_errors_uncorrected": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"device_id": "4",
|
||||
"unique_id": "600508B1001C5A6B7C8D9E0F1A2B3C4D",
|
||||
"name": "HPE LOGICAL VOLUME",
|
||||
"model": "LOGICAL VOLUME",
|
||||
"vendor": "HPE",
|
||||
"serial": "PDNLH0BRH9A1B2",
|
||||
"media_type": "Unspecified",
|
||||
"bus_type": "RAID",
|
||||
"health": "Healthy",
|
||||
"size": 1200210141184,
|
||||
"spindle": 4294967295,
|
||||
"pool": null,
|
||||
"counter": null
|
||||
},
|
||||
{
|
||||
"device_id": "",
|
||||
"unique_id": "{6b2f0c1e-0b5a-4a5e-9d3f-1c2b3a4d5e6f}",
|
||||
"name": "Data",
|
||||
"model": "Storage Space",
|
||||
"vendor": "Microsoft",
|
||||
"serial": "",
|
||||
"media_type": "Unspecified",
|
||||
"bus_type": "Spaces",
|
||||
"health": "Healthy",
|
||||
"size": 2199023255552,
|
||||
"spindle": 0,
|
||||
"pool": null,
|
||||
"counter": null
|
||||
}
|
||||
]
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"supported": true,
|
||||
"counters": true,
|
||||
"disks": [
|
||||
{
|
||||
"device_id": "0",
|
||||
"unique_id": "60022480A1B2C3D4E5F60718293A4B5C",
|
||||
"name": "Msft Virtual Disk",
|
||||
"model": "Virtual Disk",
|
||||
"vendor": "Msft",
|
||||
"serial": "",
|
||||
"media_type": "Unspecified",
|
||||
"bus_type": "SAS",
|
||||
"health": "Healthy",
|
||||
"size": 136365211648,
|
||||
"spindle": 4294967295,
|
||||
"pool": null,
|
||||
"counter": {
|
||||
"temperature": 0,
|
||||
"temperature_max": 0,
|
||||
"wear": 0,
|
||||
"power_on_hours": null,
|
||||
"read_errors_uncorrected": 0,
|
||||
"write_errors_uncorrected": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
[
|
||||
{"channel": "Application", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Application.evtx", "size": 20975616, "modified": 1764499800, "records": 41233, "type": "Administrative"},
|
||||
{"channel": "Security", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Security.evtx", "size": 20975616, "modified": 1764499990, "records": 58812, "type": "Administrative"},
|
||||
{"channel": "System", "path": "C:\\Windows\\System32\\Winevt\\Logs\\System.evtx", "size": 20975616, "modified": 1764499950, "records": 30187, "type": "Administrative"},
|
||||
{"channel": "Microsoft-Windows-Sysmon/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Sysmon%4Operational.evtx", "size": 67113984, "modified": 1764499999, "records": 120044, "type": "Operational"},
|
||||
{"channel": "Microsoft-Windows-PowerShell/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-PowerShell%4Operational.evtx", "size": 15798272, "modified": null, "records": 9120, "type": "Operational"},
|
||||
{"channel": "Microsoft-Windows-Kernel-PnP/Device Management", "path": null, "size": 69632, "modified": 1764400000, "records": 12, "type": "Operational"},
|
||||
{"channel": "Microsoft-Windows-WMI-Activity/Debug", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-WMI-Activity%4Debug.etl", "size": 4096, "modified": 1764400000, "records": 3, "type": "Debug"},
|
||||
{"channel": "Microsoft-Windows-Kernel-Boot/Analytic", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Kernel-Boot%4Analytic.etl", "size": 4096, "modified": 1764400000, "records": 7, "type": "Analytic"},
|
||||
{"channel": "Microsoft-Windows-Empty/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Empty%4Operational.evtx", "size": 69632, "modified": 1764400000, "records": 0, "type": "Operational"}
|
||||
]
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
{
|
||||
"parts": {
|
||||
"rare": {
|
||||
"ok": true,
|
||||
"capped": false,
|
||||
"events": [
|
||||
{
|
||||
"provider": "Microsoft-Windows-WER-SystemErrorReporting",
|
||||
"id": 1001,
|
||||
"time": 1764470150,
|
||||
"props": [
|
||||
"0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50)",
|
||||
"C:\\Windows\\MEMORY.DMP",
|
||||
"1130-01"
|
||||
],
|
||||
"message": "The computer has rebooted from a bugcheck. The bugcheck was: 0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50). A dump was saved in: C:\\Windows\\MEMORY.DMP. Report Id: 1130-01."
|
||||
},
|
||||
{
|
||||
"provider": "EventLog",
|
||||
"id": 6008,
|
||||
"time": 1764470040,
|
||||
"props": [
|
||||
"03:12:09",
|
||||
"\u200e30.\u200e11.\u200e2026",
|
||||
"",
|
||||
"",
|
||||
"1234",
|
||||
"",
|
||||
""
|
||||
],
|
||||
"message": "The previous system shutdown at 03:12:09 on 30.11.2026 was unexpected."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-Kernel-Power",
|
||||
"id": 41,
|
||||
"time": 1764470035,
|
||||
"props": [
|
||||
"159",
|
||||
"3",
|
||||
"18446676388826430528",
|
||||
"18446735294628329080",
|
||||
"18446676388826430800",
|
||||
"false",
|
||||
"0"
|
||||
],
|
||||
"message": "The system has rebooted without cleanly shutting down first."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-WHEA-Logger",
|
||||
"id": 18,
|
||||
"time": 1764383600,
|
||||
"props": [
|
||||
"1",
|
||||
"0",
|
||||
"5",
|
||||
"0",
|
||||
"0"
|
||||
],
|
||||
"message": "A fatal hardware error has occurred."
|
||||
},
|
||||
{
|
||||
"provider": "disk",
|
||||
"id": 7,
|
||||
"time": 1764466400,
|
||||
"props": [
|
||||
"\\Device\\Harddisk1\\DR1"
|
||||
],
|
||||
"message": "The device, \\Device\\Harddisk1\\DR1, has a bad block."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-Ntfs",
|
||||
"id": 55,
|
||||
"time": 1764462800,
|
||||
"props": [
|
||||
"D:",
|
||||
"\\Device\\HarddiskVolume5",
|
||||
"0x2"
|
||||
],
|
||||
"message": "A corruption was discovered in the file system structure on volume D:."
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-Kernel-Power",
|
||||
"id": 41,
|
||||
"time": 1764297200,
|
||||
"props": [
|
||||
"0",
|
||||
"0",
|
||||
"0",
|
||||
"0",
|
||||
"0",
|
||||
"false",
|
||||
"0"
|
||||
],
|
||||
"message": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"frequent": {
|
||||
"ok": true,
|
||||
"capped": false,
|
||||
"events": [
|
||||
{
|
||||
"provider": "Service Control Manager",
|
||||
"id": 7031,
|
||||
"time": 1764470600,
|
||||
"props": [
|
||||
"Backup Agent",
|
||||
"1",
|
||||
"60000",
|
||||
"1",
|
||||
"Restart the service"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-WHEA-Logger",
|
||||
"id": 47,
|
||||
"time": 1764470500,
|
||||
"props": [
|
||||
"3",
|
||||
"0",
|
||||
"1"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "disk",
|
||||
"id": 153,
|
||||
"time": 1764470400,
|
||||
"props": [
|
||||
"\\Device\\Harddisk1\\DR1",
|
||||
"0x1d4c0",
|
||||
"1",
|
||||
"\\Device\\00000034"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Service Control Manager",
|
||||
"id": 7034,
|
||||
"time": 1764470300,
|
||||
"props": [
|
||||
"Vendor Sync",
|
||||
"2"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Microsoft-Windows-WHEA-Logger",
|
||||
"id": 19,
|
||||
"time": 1764470200,
|
||||
"props": [
|
||||
"3",
|
||||
"0",
|
||||
"1"
|
||||
],
|
||||
"message": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"apps": {
|
||||
"ok": true,
|
||||
"capped": false,
|
||||
"events": [
|
||||
{
|
||||
"provider": "Application Error",
|
||||
"id": 1000,
|
||||
"time": 1764470900,
|
||||
"props": [
|
||||
"vendorapp.exe",
|
||||
"4.2.0.0",
|
||||
"65a1b2c3",
|
||||
"ntdll.dll",
|
||||
"10.0.20348.2340",
|
||||
"f0e1d2c3",
|
||||
"c0000005",
|
||||
"00000000000a1b2c",
|
||||
"1f40",
|
||||
"01db1234567890ab",
|
||||
"C:\\Program Files\\Vendor\\vendorapp.exe"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Application Error",
|
||||
"id": 1000,
|
||||
"time": 1764470800,
|
||||
"props": [
|
||||
"vendorapp.exe",
|
||||
"4.2.0.0",
|
||||
"65a1b2c3",
|
||||
"ntdll.dll",
|
||||
"10.0.20348.2340",
|
||||
"f0e1d2c3",
|
||||
"c0000005",
|
||||
"00000000000a1b2c",
|
||||
"1f40",
|
||||
"01db1234567890ab",
|
||||
"C:\\Program Files\\Vendor\\vendorapp.exe"
|
||||
],
|
||||
"message": null
|
||||
},
|
||||
{
|
||||
"provider": "Application Error",
|
||||
"id": 1000,
|
||||
"time": 1764470700,
|
||||
"props": [
|
||||
"legacy.exe",
|
||||
"1.0.0.0",
|
||||
"5f0a0b0c"
|
||||
],
|
||||
"message": null
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -1,7 +1,11 @@
|
||||
[
|
||||
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234},
|
||||
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0},
|
||||
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321},
|
||||
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0},
|
||||
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null}
|
||||
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234, "exit_code": 0, "service_code": 0, "account": "NT AUTHORITY\\NetworkService", "trigger_start": false},
|
||||
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
|
||||
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321, "exit_code": 0, "service_code": 0, "account": "CORP\\svc-sql", "trigger_start": false},
|
||||
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "NT AUTHORITY\\LocalService", "trigger_start": true},
|
||||
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": true},
|
||||
{"name": "AppReadiness", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
|
||||
{"name": "BackupAgent", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1067, "service_code": 0, "account": "CORP\\svc-backup", "trigger_start": false},
|
||||
{"name": "VendorSync", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1066, "service_code": 2147942405, "account": "LocalSystem", "trigger_start": false},
|
||||
{"name": "BthServ", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1, "service_code": 0, "account": null, "trigger_start": true}
|
||||
]
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"supported": true,
|
||||
"pools": [
|
||||
{
|
||||
"name": "Pool1",
|
||||
"health": "Warning",
|
||||
"operational": [
|
||||
"Degraded"
|
||||
],
|
||||
"size": 8001574060032,
|
||||
"allocated": 2199023255552,
|
||||
"resiliency": "Mirror",
|
||||
"read_only": false,
|
||||
"disks": [
|
||||
{
|
||||
"device_id": "1",
|
||||
"unique_id": "50014EE2B1C2D3E4"
|
||||
},
|
||||
{
|
||||
"device_id": "3",
|
||||
"unique_id": "50014EE2B1C2D3F5"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
{
|
||||
"supported": true,
|
||||
"volumes": [
|
||||
{
|
||||
"letter": "C",
|
||||
"label": "",
|
||||
"file_system": "NTFS",
|
||||
"size": 999483936768,
|
||||
"remaining": 712345698304,
|
||||
"health": "Healthy",
|
||||
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-100000000000}\\",
|
||||
"mounts": [
|
||||
"C:\\"
|
||||
]
|
||||
},
|
||||
{
|
||||
"letter": "D",
|
||||
"label": "Data",
|
||||
"file_system": "ReFS",
|
||||
"size": 2196875771904,
|
||||
"remaining": 109521666048,
|
||||
"health": "Warning",
|
||||
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-200000000000}\\",
|
||||
"mounts": [
|
||||
"D:\\"
|
||||
]
|
||||
},
|
||||
{
|
||||
"letter": "",
|
||||
"label": "Logs",
|
||||
"file_system": "NTFS",
|
||||
"size": 1200191766528,
|
||||
"remaining": 1100000000000,
|
||||
"health": "Healthy",
|
||||
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-300000000000}\\",
|
||||
"mounts": [
|
||||
"C:\\Logs\\"
|
||||
]
|
||||
},
|
||||
{
|
||||
"letter": "",
|
||||
"label": "",
|
||||
"file_system": "FAT32",
|
||||
"size": 104857600,
|
||||
"remaining": 71303168,
|
||||
"health": "Healthy",
|
||||
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-400000000000}\\",
|
||||
"mounts": []
|
||||
},
|
||||
{
|
||||
"letter": "",
|
||||
"label": "",
|
||||
"file_system": "NTFS",
|
||||
"size": 681574400,
|
||||
"remaining": 98566144,
|
||||
"health": "Healthy",
|
||||
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-500000000000}\\",
|
||||
"mounts": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
"""The event channels as the host's log sources (NetOrk/netork#2897).
|
||||
|
||||
A Windows host keeps its logs in event channels. ``Get-WinEvent -ListLog *`` names
|
||||
every one with its ``.evtx`` file, size, last write and record count; a channel that
|
||||
is switched on and holds records is a log the host writes. Analytic and debug
|
||||
channels are trace sessions, not logs a reader can follow, and are left out. The
|
||||
answer is the shape of tests/fixtures/synthetic/event_channels.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import event_channels as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "event_channels.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading(answer: str | None = None) -> dict:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
|
||||
return d.get_log_sources()
|
||||
|
||||
|
||||
class TestTheReading:
|
||||
def test_read_as_an_administrator_without_a_journal(self):
|
||||
reading = _reading()
|
||||
assert (reading["attributed"], reading["journald"], reading["forwarding"]) == (
|
||||
True,
|
||||
False,
|
||||
None,
|
||||
)
|
||||
|
||||
def test_every_channel_with_records_sorted_by_name(self):
|
||||
assert [s["channel"] for s in _reading()["sources"]] == [
|
||||
"Application",
|
||||
"Microsoft-Windows-Kernel-PnP/Device Management",
|
||||
"Microsoft-Windows-PowerShell/Operational",
|
||||
"Microsoft-Windows-Sysmon/Operational",
|
||||
"Security",
|
||||
"System",
|
||||
]
|
||||
|
||||
def test_a_channel_is_an_eventlog_source(self):
|
||||
sysmon = next(s for s in _reading()["sources"] if "Sysmon" in s["channel"])
|
||||
assert sysmon == {
|
||||
"kind": "eventlog",
|
||||
"path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx",
|
||||
"unit": None,
|
||||
"container_id": None,
|
||||
"process": None,
|
||||
"size": 67113984,
|
||||
"modified": "2025-11-30T10:53:19+00:00",
|
||||
"channel": "Microsoft-Windows-Sysmon/Operational",
|
||||
}
|
||||
|
||||
def test_what_the_host_did_not_say_is_none(self):
|
||||
sources = {s["channel"]: s for s in _reading()["sources"]}
|
||||
assert sources["Microsoft-Windows-PowerShell/Operational"]["modified"] is None
|
||||
assert sources["Microsoft-Windows-Kernel-PnP/Device Management"]["path"] is None
|
||||
|
||||
@pytest.mark.parametrize("left_out", ["Debug", "Analytic", "Empty"])
|
||||
def test_trace_sessions_and_empty_channels_are_left_out(self, left_out):
|
||||
assert not any(left_out in s["channel"] for s in _reading()["sources"])
|
||||
|
||||
def test_a_single_channel_is_still_a_list(self):
|
||||
one = json.loads(FIXTURE.read_text())[2]
|
||||
assert [s["channel"] for s in _reading(json.dumps(one))["sources"]] == ["System"]
|
||||
|
||||
def test_no_channel_is_no_sources(self):
|
||||
assert _reading("")["sources"] == []
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
def test_lists_every_channel_once(self):
|
||||
assert "Get-WinEvent -ListLog *" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_a_channel_it_may_not_open_costs_only_that_channel(self):
|
||||
assert "-ErrorAction SilentlyContinue" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_only_channels_switched_on_and_holding_records(self):
|
||||
assert "$_.IsEnabled -and $_.RecordCount" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_the_file_is_named_as_it_is_on_disk(self):
|
||||
assert "ExpandEnvironmentVariables" in mod._PS_EVENT_CHANNELS
|
||||
|
||||
def test_a_list_goes_through_input_object(self):
|
||||
assert "-InputObject @(" in mod._PS_EVENT_CHANNELS
|
||||
@@ -0,0 +1,206 @@
|
||||
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
|
||||
|
||||
One script asks the event log three questions over the reading's window: the rare
|
||||
events of the System log (an unexpected shutdown, a bugcheck, a fatal hardware
|
||||
error, a bad block, a file system corruption), its frequent ones (corrected
|
||||
hardware errors, retried disk I/O, services that ended unexpectedly) and the
|
||||
Application log's crashing programs. Each is bounded by time and count, and each
|
||||
catches ``NoMatchingEventsFound``: ``Get-WinEvent`` throws when nothing matches. The
|
||||
answer is the shape of tests/fixtures/synthetic/host_events.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import HOST_EVENT_KINDS, HostEventsMixin
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import host_events as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_events.json"
|
||||
NOW = 1764500000.0
|
||||
WEEK = 7 * 86400
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _driver(answer: dict[str, Any] | str | None = None) -> WindowsDriver:
|
||||
if answer is None:
|
||||
answer = FIXTURE.read_text()
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(answer if isinstance(answer, str) else json.dumps(answer))
|
||||
return d
|
||||
|
||||
|
||||
def _fixture() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _now(monkeypatch):
|
||||
monkeypatch.setattr(mod.time, "time", lambda: NOW)
|
||||
|
||||
|
||||
def _kinds(reading) -> list[tuple[str, str | None]]:
|
||||
return [(e["kind"], e["subject"]) for e in reading["events"]]
|
||||
|
||||
|
||||
class TestTheEvents:
|
||||
def test_every_event_as_its_kind_and_subject_newest_first(self):
|
||||
assert _kinds(_driver().get_host_events()) == [
|
||||
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
|
||||
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
|
||||
("app_crash", "legacy.exe"),
|
||||
("service_crash", "Backup Agent"),
|
||||
("hardware_error_corrected", None),
|
||||
("disk_error", r"\Device\Harddisk1\DR1"),
|
||||
("service_crash", "Vendor Sync"),
|
||||
("hardware_error_corrected", None),
|
||||
("system_crash", "0x0000009f"),
|
||||
("unexpected_shutdown", None),
|
||||
("unexpected_shutdown", "0x0000009f"),
|
||||
("disk_error", r"\Device\Harddisk1\DR1"),
|
||||
("disk_error", "D:"),
|
||||
("hardware_error_fatal", None),
|
||||
("unexpected_shutdown", None),
|
||||
]
|
||||
|
||||
def test_an_event_says_when_where_and_what_the_host_wrote(self):
|
||||
crash = next(
|
||||
e for e in _driver().get_host_events()["events"] if e["kind"] == "system_crash"
|
||||
)
|
||||
assert crash == {
|
||||
"kind": "system_crash",
|
||||
"time": "2025-11-30T02:35:50+00:00",
|
||||
"subject": "0x0000009f",
|
||||
"source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001",
|
||||
"message": crash["message"],
|
||||
}
|
||||
assert crash["message"].startswith("The computer has rebooted from a bugcheck.")
|
||||
|
||||
def test_a_power_loss_without_a_bugcheck_has_no_stop_code(self):
|
||||
shutdowns = [
|
||||
e for e in _driver().get_host_events()["events"] if e["kind"] == "unexpected_shutdown"
|
||||
]
|
||||
assert [e["subject"] for e in shutdowns] == [None, "0x0000009f", None]
|
||||
|
||||
def test_the_hosts_message_is_cut(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["rare"]["events"][0]["message"] = "y" * 5000
|
||||
events = _driver(answer).get_host_events()["events"]
|
||||
assert max(len(e["message"] or "") for e in events) == 300
|
||||
|
||||
def test_an_event_the_reading_does_not_know_is_left_out(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["rare"]["events"] = [
|
||||
{"provider": "Microsoft-Windows-Kernel-General", "id": 12, "time": NOW, "props": []}
|
||||
]
|
||||
kinds = {e["kind"] for e in _driver(answer).get_host_events()["events"]}
|
||||
assert "unexpected_shutdown" not in kinds
|
||||
|
||||
def test_a_single_event_is_still_a_list(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["apps"]["events"] = answer["parts"]["apps"]["events"][0]
|
||||
apps = [e for e in _driver(answer).get_host_events()["events"] if e["kind"] == "app_crash"]
|
||||
assert len(apps) == 1
|
||||
|
||||
|
||||
class TestWhatWasRead:
|
||||
def test_a_full_reading_names_nothing_capped_or_unread(self):
|
||||
reading = _driver().get_host_events()
|
||||
assert (reading["capped"], reading["unread"]) == ([], [])
|
||||
|
||||
def test_an_empty_log_is_no_events_not_an_error(self):
|
||||
"""What the script makes of ``NoMatchingEventsFound``: read, nothing found."""
|
||||
answer = _fixture()
|
||||
for part in answer["parts"].values():
|
||||
part["events"] = []
|
||||
reading = _driver(answer).get_host_events()
|
||||
assert (reading["events"], reading["unread"]) == ([], [])
|
||||
|
||||
def test_a_query_that_failed_names_its_kinds_unread(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["frequent"] = {"ok": False, "capped": False, "events": [], "error": "x"}
|
||||
reading = _driver(answer).get_host_events()
|
||||
assert reading["unread"] == ["hardware_error_corrected", "disk_error", "service_crash"]
|
||||
assert "service_crash" not in {e["kind"] for e in reading["events"]}
|
||||
|
||||
def test_a_query_read_up_to_its_bound_names_its_kinds_capped(self):
|
||||
answer = _fixture()
|
||||
answer["parts"]["apps"]["capped"] = True
|
||||
assert _driver(answer).get_host_events()["capped"] == ["app_crash"]
|
||||
|
||||
def test_a_part_missing_from_the_answer_is_unread(self):
|
||||
answer = _fixture()
|
||||
del answer["parts"]["apps"]
|
||||
assert _driver(answer).get_host_events()["unread"] == ["app_crash"]
|
||||
|
||||
def test_every_kind_is_read_by_some_query(self):
|
||||
read = {kind for kinds in mod._PART_KINDS.values() for kind in kinds}
|
||||
assert read == set(HOST_EVENT_KINDS)
|
||||
|
||||
@pytest.mark.parametrize("answer", ["", "[]", '{"since": 1}'])
|
||||
def test_an_answer_without_a_report_raises(self, answer):
|
||||
with pytest.raises(ValueError):
|
||||
_driver(answer).get_host_events()
|
||||
|
||||
|
||||
class TestTheWindow:
|
||||
def test_a_week_by_default(self):
|
||||
d = _driver()
|
||||
reading = d.get_host_events()
|
||||
assert reading["since"] == "2025-11-23T10:53:20+00:00"
|
||||
assert "@SystemTime>='2025-11-23T10:53:20.000Z'" in d._transport.sent[0]
|
||||
|
||||
def test_the_callers_start(self):
|
||||
d = _driver()
|
||||
reading = d.get_host_events(since=NOW - 3600)
|
||||
assert reading["since"] == "2025-11-30T09:53:20+00:00"
|
||||
assert "@SystemTime>='2025-11-30T09:53:20.000Z'" in d._transport.sent[0]
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
script = mod.host_events_script(NOW - WEEK)
|
||||
|
||||
def test_every_query_catches_no_matching_events(self):
|
||||
assert self.script.count("Get-WinEvent") == 1
|
||||
assert "NoMatchingEventsFound" in self.script
|
||||
assert len(re.findall(r"\(Q '(System|Application)'", self.script)) == 3
|
||||
|
||||
def test_every_query_is_bounded_by_count(self):
|
||||
bounds = [int(n) for n in re.findall(r"\(Q '\w+' \$\w+ (\d+)", self.script)]
|
||||
assert bounds == [100, 500, 200]
|
||||
assert "-MaxEvents $max" in self.script
|
||||
|
||||
def test_every_query_is_bounded_by_time(self):
|
||||
assert self.script.count("TimeCreated[@SystemTime>=") == 3
|
||||
|
||||
def test_only_the_rare_events_carry_their_message(self):
|
||||
assert re.findall(r"\(Q '\w+' \$\w+ \d+ \$(true|false)\)", self.script) == [
|
||||
"true",
|
||||
"false",
|
||||
"false",
|
||||
]
|
||||
|
||||
def test_the_answer_survives_a_deep_object(self):
|
||||
assert "-Depth 6" in self.script
|
||||
|
||||
def test_stops_on_errors_it_does_not_catch(self):
|
||||
assert self.script.lstrip().startswith("$ErrorActionPreference = 'Stop'")
|
||||
|
||||
def test_the_driver_carries_the_contract(self):
|
||||
assert isinstance(WindowsDriver("h", "u", "p"), HostEventsMixin)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""The host's services and how each one's last run ended (NetOrk/netork#2897).
|
||||
|
||||
``Win32_Service`` says whether a service runs and how it starts, and also what its
|
||||
last run ended with: ``ExitCode`` (``1066`` hands over to
|
||||
``ServiceSpecificExitCode``, ``1077`` is "not started since boot"). Together with
|
||||
whether a trigger starts it (a ``TriggerInfo`` key under the service) that tells a
|
||||
service that died from one stopped on purpose. The reading is the shape of
|
||||
tests/fixtures/synthetic/services.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import services as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "services.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer if script == mod._PS_SERVICES else ""
|
||||
|
||||
|
||||
def _services(answer: str | None = None) -> dict[str, dict]:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
|
||||
return {s["name"]: s for s in d.get_services()}
|
||||
|
||||
|
||||
class TestRunningAndEnabled:
|
||||
def test_maps_state_and_start_mode(self):
|
||||
services = _services()
|
||||
assert {n: (s["running"], s["enabled"], s["pid"]) for n, s in services.items()} == {
|
||||
"WinRM": (True, True, 1234),
|
||||
"Spooler": (False, False, 0),
|
||||
"MSSQL$SQLEXPRESS": (True, True, 4321),
|
||||
"RemoteRegistry": (False, False, 0),
|
||||
"wuauserv": (False, False, 0),
|
||||
"AppReadiness": (False, True, 0),
|
||||
"BackupAgent": (False, True, 0),
|
||||
"VendorSync": (False, True, 0),
|
||||
"BthServ": (False, True, 0),
|
||||
}
|
||||
|
||||
def test_a_single_service_is_still_a_list(self):
|
||||
one = json.loads(FIXTURE.read_text())[0]
|
||||
assert list(_services(json.dumps(one))) == ["WinRM"]
|
||||
|
||||
def test_nothing_read_is_no_services(self):
|
||||
assert _services("") == {}
|
||||
|
||||
|
||||
class TestHowTheLastRunEnded:
|
||||
def test_a_running_service_succeeded(self):
|
||||
assert _services()["WinRM"] == {
|
||||
"name": "WinRM",
|
||||
"running": True,
|
||||
"enabled": True,
|
||||
"pid": 1234,
|
||||
"result": "success",
|
||||
"exit_code": None,
|
||||
"trigger_start": False,
|
||||
"account": "NT AUTHORITY\\NetworkService",
|
||||
}
|
||||
|
||||
def test_one_stopped_on_purpose_succeeded(self):
|
||||
assert (_services()["Spooler"]["result"], _services()["Spooler"]["exit_code"]) == (
|
||||
"success",
|
||||
None,
|
||||
)
|
||||
|
||||
def test_one_not_started_since_boot_has_no_result(self):
|
||||
"""1077: a delayed or a demand-start service that has not run yet."""
|
||||
service = _services()["AppReadiness"]
|
||||
assert (service["result"], service["exit_code"]) == (None, None)
|
||||
|
||||
def test_one_that_died_ended_with_its_exit_code(self):
|
||||
"""1067: the process terminated unexpectedly."""
|
||||
service = _services()["BackupAgent"]
|
||||
assert (service["result"], service["exit_code"]) == ("exit-code", 1067)
|
||||
|
||||
def test_a_service_specific_error_is_the_services_own_code(self):
|
||||
service = _services()["VendorSync"]
|
||||
assert (service["result"], service["exit_code"]) == ("exit-code", 2147942405)
|
||||
|
||||
def test_a_trigger_start_service_says_so(self):
|
||||
assert _services()["BthServ"]["trigger_start"] is True
|
||||
assert _services()["BackupAgent"]["trigger_start"] is False
|
||||
|
||||
def test_the_account_it_runs_as(self):
|
||||
assert _services()["BackupAgent"]["account"] == "CORP\\svc-backup"
|
||||
assert _services()["BthServ"]["account"] is None
|
||||
|
||||
def test_a_reading_without_the_new_fields_says_nothing_of_them(self):
|
||||
"""An older script's answer: running and enabled only, nothing invented."""
|
||||
old = [{"name": "WinRM", "state": "Stopped", "start_mode": "Auto", "pid": 0}]
|
||||
service = _services(json.dumps(old))["WinRM"]
|
||||
assert (service["result"], service["exit_code"], service["trigger_start"]) == (
|
||||
None,
|
||||
None,
|
||||
False,
|
||||
)
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
def test_exit_codes_leave_the_host_as_wide_integers(self):
|
||||
"""``ServiceSpecificExitCode`` is a UInt32: ``[int]`` would throw on an HRESULT."""
|
||||
assert "[int64]$_.ExitCode" in mod._PS_SERVICES
|
||||
assert "[int64]$_.ServiceSpecificExitCode" in mod._PS_SERVICES
|
||||
|
||||
def test_trigger_start_is_read_once_from_the_registry(self):
|
||||
assert r"Services\*\TriggerInfo" in mod._PS_SERVICES
|
||||
assert "-ErrorAction SilentlyContinue" in mod._PS_SERVICES
|
||||
|
||||
def test_a_list_goes_through_input_object(self):
|
||||
assert "-InputObject @(" in mod._PS_SERVICES
|
||||
@@ -1,317 +0,0 @@
|
||||
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
|
||||
|
||||
Each reading is one script whose JSON a fake host answers from
|
||||
tests/fixtures/synthetic/: ``disks_server.json`` (an NVMe SSD, two SATA disks in a
|
||||
Storage Spaces pool, a RAID controller's logical disk and a Storage Spaces virtual
|
||||
disk), ``disks_vm.json`` (a Hyper-V guest's virtual disk with empty reliability
|
||||
counters), ``storage_pools.json`` and ``volumes.json``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import HostStorageMixin, OSDriver
|
||||
from napalm_device_types.roles import primary_role_of, role_keys_of
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import storage as mod
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
||||
|
||||
|
||||
def _load(name: str) -> Any:
|
||||
return json.loads((FIXTURES / name).read_text())
|
||||
|
||||
|
||||
class FakeHost:
|
||||
"""Answers each storage script with *answers*' entry for it."""
|
||||
|
||||
def __init__(self, answers: dict[str, Any]) -> None:
|
||||
self.answers = answers
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
answer = self.answers[script]
|
||||
return answer if isinstance(answer, str) else json.dumps(answer)
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _driver(**answers: Any) -> WindowsDriver:
|
||||
scripts = {
|
||||
"disks": mod._PS_DISKS,
|
||||
"pools": mod._PS_STORAGE_POOLS,
|
||||
"volumes": mod._PS_VOLUMES,
|
||||
}
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeHost({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
|
||||
return d
|
||||
|
||||
|
||||
def _server() -> WindowsDriver:
|
||||
return _driver(
|
||||
disks=_load("disks_server.json"),
|
||||
pools=_load("storage_pools.json"),
|
||||
volumes=_load("volumes.json"),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestContract:
|
||||
def test_a_host_with_storage_stays_a_host(self):
|
||||
assert issubclass(WindowsDriver, HostStorageMixin)
|
||||
assert "storage" not in role_keys_of(WindowsDriver)
|
||||
assert primary_role_of(WindowsDriver) == primary_role_of(OSDriver)
|
||||
|
||||
def test_every_getter_is_there(self):
|
||||
for name in ("get_disks", "get_disk_pools", "get_volumes", "get_disk_smart"):
|
||||
assert callable(getattr(WindowsDriver, name)), name
|
||||
|
||||
@pytest.mark.parametrize("script", ["_PS_DISKS", "_PS_STORAGE_POOLS", "_PS_VOLUMES"])
|
||||
def test_scripts_follow_the_driver_conventions(self, script):
|
||||
text = getattr(mod, script)
|
||||
assert "$ErrorActionPreference = 'Stop'" in text
|
||||
assert "ConvertTo-Json" in text
|
||||
assert "Get-Command" in text # a missing cmdlet is "not supported", not an error
|
||||
|
||||
def test_counters_are_read_per_disk_and_may_fail(self):
|
||||
"""Get-StorageReliabilityCounter needs an administrator and is missing on some
|
||||
virtual disks: one disk's failure is that disk's missing counter."""
|
||||
assert "try { $counter = $disk | Get-StorageReliabilityCounter }" in mod._PS_DISKS
|
||||
assert "catch { $counter = $null }" in mod._PS_DISKS
|
||||
|
||||
def test_no_smartctl(self):
|
||||
for script in (mod._PS_DISKS, mod._PS_STORAGE_POOLS, mod._PS_VOLUMES):
|
||||
assert "smartctl" not in script
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_disks
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDisks:
|
||||
def test_an_nvme_ssd(self):
|
||||
disk = _server().get_disks()[0]
|
||||
assert disk == {
|
||||
"slot": "PhysicalDisk0",
|
||||
"model": "Samsung SSD 980 PRO 1TB",
|
||||
"serial": "0025_385A_11B2_2C33.",
|
||||
"vendor": "",
|
||||
"type": "nvme",
|
||||
"size": 1000204886016,
|
||||
"rpm": 0,
|
||||
"temperature": 41,
|
||||
"health": "healthy",
|
||||
"pool": "",
|
||||
}
|
||||
|
||||
def test_a_pool_member_with_a_warning(self):
|
||||
disk = _server().get_disks()[1]
|
||||
assert disk["slot"] == "PhysicalDisk1"
|
||||
assert disk["serial"] == "WD-WCC7K1ABCDEF" # ATA serials come padded
|
||||
assert (disk["type"], disk["rpm"], disk["temperature"]) == ("hdd", 5400, 36)
|
||||
assert (disk["health"], disk["pool"]) == ("warning", "Pool1")
|
||||
|
||||
def test_a_zero_temperature_and_an_unknown_speed_are_unknown(self):
|
||||
disk = _server().get_disks()[2]
|
||||
assert (disk["temperature"], disk["rpm"]) == (-1, 0)
|
||||
assert disk["health"] == "healthy" # a real disk with thin counters keeps its verdict
|
||||
|
||||
def test_a_raid_logical_disk_has_no_drive_health(self):
|
||||
"""Windows calls the controller's logical disk Healthy; that is no drive's verdict."""
|
||||
disk = _server().get_disks()[3]
|
||||
assert (disk["type"], disk["temperature"], disk["health"]) == ("unknown", -1, "unknown")
|
||||
|
||||
def test_a_storage_spaces_virtual_disk_is_no_physical_disk(self):
|
||||
slots = [d["slot"] for d in _server().get_disks()]
|
||||
assert slots == ["PhysicalDisk0", "PhysicalDisk1", "PhysicalDisk3", "PhysicalDisk4"]
|
||||
|
||||
def test_a_virtual_disk_with_empty_counters(self):
|
||||
"""Temperature -1 and health "unknown", not zeros and not a "healthy" nobody
|
||||
measured."""
|
||||
[disk] = _driver(disks=_load("disks_vm.json")).get_disks()
|
||||
assert disk["temperature"] == -1
|
||||
assert disk["health"] == "unknown"
|
||||
assert disk["type"] == "unknown"
|
||||
|
||||
def test_bad_news_is_never_unknown(self):
|
||||
raw = _load("disks_vm.json")
|
||||
raw["disks"][0]["health"] = "Unhealthy"
|
||||
assert _driver(disks=raw).get_disks()[0]["health"] == "failed"
|
||||
|
||||
def test_a_disk_without_a_number_is_named_by_its_id(self):
|
||||
raw = _load("disks_vm.json")
|
||||
raw["disks"][0]["device_id"] = ""
|
||||
slot = _driver(disks=raw).get_disks()[0]["slot"]
|
||||
assert slot == "60022480A1B2C3D4E5F60718293A4B5C"
|
||||
|
||||
def test_without_the_storage_module_there_are_none(self):
|
||||
assert _driver(disks={"supported": False}).get_disks() == []
|
||||
|
||||
def test_an_empty_answer_could_not_look(self):
|
||||
with pytest.raises(ValueError, match="disk reading came back empty"):
|
||||
_driver(disks="").get_disks()
|
||||
|
||||
def test_one_disk_arrives_bare(self):
|
||||
"""ConvertTo-Json unwraps a one-element array; the parse wraps it again."""
|
||||
raw = _load("disks_vm.json")
|
||||
raw["disks"] = raw["disks"][0]
|
||||
assert len(_driver(disks=raw).get_disks()) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_disk_smart
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDiskSmart:
|
||||
def test_the_reliability_counters_of_an_nvme_ssd(self):
|
||||
smart = _server().get_disk_smart()
|
||||
assert smart["PhysicalDisk0"] == {
|
||||
"model": "Samsung SSD 980 PRO 1TB",
|
||||
"serial": "0025_385A_11B2_2C33.",
|
||||
"type": "nvme",
|
||||
"size": 1000204886016,
|
||||
"health": "ok",
|
||||
"wearout": None,
|
||||
"temperature": 41,
|
||||
"percentage_used": 3,
|
||||
"available_spare": None,
|
||||
"reallocated_sectors": None,
|
||||
"power_on_hours": 5120,
|
||||
"temperature_max": 68,
|
||||
"read_errors_uncorrected": 0,
|
||||
"write_errors_uncorrected": 0,
|
||||
}
|
||||
|
||||
def test_a_disk_with_errors_and_a_warning(self):
|
||||
entry = _server().get_disk_smart()["PhysicalDisk1"]
|
||||
assert entry["health"] == "warning"
|
||||
assert entry["read_errors_uncorrected"] == 12
|
||||
assert entry["percentage_used"] is None # a spinning disk does not wear out by writes
|
||||
|
||||
def test_thin_counters_are_none_where_empty(self):
|
||||
entry = _server().get_disk_smart()["PhysicalDisk3"]
|
||||
assert entry["temperature"] is None
|
||||
assert entry["power_on_hours"] == 30990
|
||||
assert entry["read_errors_uncorrected"] is None
|
||||
|
||||
def test_disks_that_report_nothing_are_left_out(self):
|
||||
assert set(_server().get_disk_smart()) == {
|
||||
"PhysicalDisk0",
|
||||
"PhysicalDisk1",
|
||||
"PhysicalDisk3",
|
||||
}
|
||||
|
||||
def test_a_virtual_host_has_no_drive_health(self):
|
||||
assert _driver(disks=_load("disks_vm.json")).get_disk_smart() == {}
|
||||
|
||||
def test_without_the_counter_cmdlet_there_is_none(self):
|
||||
raw = _load("disks_server.json")
|
||||
raw["counters"] = False
|
||||
for disk in raw["disks"]:
|
||||
disk["counter"] = None
|
||||
assert _driver(disks=raw).get_disk_smart() == {}
|
||||
|
||||
def test_without_the_storage_module_there_is_none(self):
|
||||
assert _driver(disks={"supported": False}).get_disk_smart() == {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_disk_pools
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPools:
|
||||
def test_a_degraded_mirror(self):
|
||||
assert _server().get_disk_pools() == {
|
||||
"Pool1": {
|
||||
"name": "Pool1",
|
||||
"type": "storage-spaces",
|
||||
"level": "mirror",
|
||||
"status": "degraded",
|
||||
"total": 8001574060032,
|
||||
"used": 2199023255552,
|
||||
"available": 5802550804480,
|
||||
"disks": ["PhysicalDisk1", "PhysicalDisk3"],
|
||||
"auto_expand": False,
|
||||
"dedup": False,
|
||||
"compression": "off",
|
||||
}
|
||||
}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("health", "resiliency", "status", "level"),
|
||||
[
|
||||
("Healthy", "Simple", "online", "stripe"),
|
||||
("Unhealthy", "Parity", "faulted", "parity"),
|
||||
("Unknown", "", "unknown", "unknown"),
|
||||
],
|
||||
)
|
||||
def test_status_and_level(self, health, resiliency, status, level):
|
||||
raw = _load("storage_pools.json")
|
||||
raw["pools"][0].update(health=health, resiliency=resiliency)
|
||||
pool = _driver(pools=raw).get_disk_pools()["Pool1"]
|
||||
assert (pool["status"], pool["level"]) == (status, level)
|
||||
|
||||
def test_no_pools(self):
|
||||
assert _driver(pools={"supported": True, "pools": []}).get_disk_pools() == {}
|
||||
|
||||
def test_without_storage_spaces_there_are_none(self):
|
||||
assert _driver(pools={"supported": False}).get_disk_pools() == {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_volumes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestVolumes:
|
||||
def test_the_system_drive(self):
|
||||
assert _server().get_volumes()["C:"] == {
|
||||
"name": "C:",
|
||||
"pool": "",
|
||||
"type": "filesystem",
|
||||
"total": 999483936768,
|
||||
"used": 287138238464,
|
||||
"available": 712345698304,
|
||||
"mountpoint": "C:\\",
|
||||
"compression": "",
|
||||
"dedup": False,
|
||||
"readonly": False,
|
||||
"snapshots": 0,
|
||||
"file_system": "NTFS",
|
||||
"health": "healthy",
|
||||
}
|
||||
|
||||
def test_a_labelled_volume_with_a_warning(self):
|
||||
volume = _server().get_volumes()["D:"]
|
||||
assert (volume["name"], volume["file_system"]) == ("Data", "ReFS")
|
||||
assert volume.get("health") == "warning"
|
||||
|
||||
def test_a_volume_mounted_in_a_folder(self):
|
||||
volume = _server().get_volumes()["C:\\Logs"]
|
||||
assert (volume["name"], volume["mountpoint"]) == ("Logs", "C:\\Logs\\")
|
||||
|
||||
def test_volumes_mounted_nowhere_are_left_out(self):
|
||||
"""The EFI system partition and the recovery partition hold no one's data."""
|
||||
assert list(_server().get_volumes()) == ["C:", "D:", "C:\\Logs"]
|
||||
|
||||
def test_without_the_storage_module_there_are_none(self):
|
||||
assert _driver(volumes={"supported": False}).get_volumes() == {}
|
||||
|
||||
def test_an_empty_answer_could_not_look(self):
|
||||
with pytest.raises(ValueError, match="volume reading came back empty"):
|
||||
_driver(volumes="").get_volumes()
|
||||
@@ -370,19 +370,6 @@ class TestGetRouteTo:
|
||||
assert list(routes) == ["192.168.50.0/24"]
|
||||
|
||||
|
||||
class TestGetServices:
|
||||
def test_maps_state_and_start_mode(self):
|
||||
services = _driver(_PS_SERVICES=_fixture("services.json")).get_services()
|
||||
|
||||
assert services == [
|
||||
{"name": "WinRM", "running": True, "enabled": True, "pid": 1234},
|
||||
{"name": "Spooler", "running": False, "enabled": False, "pid": 0},
|
||||
{"name": "MSSQL$SQLEXPRESS", "running": True, "enabled": True, "pid": 4321},
|
||||
{"name": "RemoteRegistry", "running": False, "enabled": False, "pid": 0},
|
||||
{"name": "wuauserv", "running": False, "enabled": False, "pid": 0},
|
||||
]
|
||||
|
||||
|
||||
class TestGetListeningSockets:
|
||||
"""netOrk #673: what listens, and which Windows service it is."""
|
||||
|
||||
|
||||
+12
-5
@@ -13,8 +13,16 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
from napalm_windows import WindowsDriver, scheduled_tasks, storage, time_sync
|
||||
from napalm_windows import (
|
||||
WindowsDriver,
|
||||
event_channels,
|
||||
host_events,
|
||||
scheduled_tasks,
|
||||
services,
|
||||
time_sync,
|
||||
)
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
SCRIPTS = {
|
||||
@@ -23,13 +31,12 @@ SCRIPTS = {
|
||||
"interfaces_ip": mod._PS_INTERFACES_IP,
|
||||
"arp": mod._PS_ARP,
|
||||
"routes": mod._PS_ROUTES,
|
||||
"services": mod._PS_SERVICES,
|
||||
"services": services._PS_SERVICES,
|
||||
"listening": mod._PS_LISTENING,
|
||||
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
|
||||
"time_sync": time_sync._PS_TIME_SYNC,
|
||||
"disks": storage._PS_DISKS,
|
||||
"storage_pools": storage._PS_STORAGE_POOLS,
|
||||
"volumes": storage._PS_VOLUMES,
|
||||
"host_events": host_events.host_events_script(time.time() - 7 * 86400),
|
||||
"event_channels": event_channels._PS_EVENT_CHANNELS,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
Reference in new issue
Block a user