"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891). :class:`WindowsHostStatusMixin` gives the driver napalm-device-types' ``get_host_status`` (``HostStatusDict``) in one script. Each part is read on its own -- a COM object that does not answer over WinRM leaves the rest standing -- and nothing searches for updates: that is the update reading's, and too slow for a poll. **Restart required** is what Windows says about its own updates: * Windows Update's ``Microsoft.Update.SystemInfo.RebootRequired``, and its registry marker ``WindowsUpdate\\Auto Update\\RebootRequired`` where the COM object did not answer; * component-based servicing's ``RebootPending`` (features, roles, servicing stack). Other markers only explain: ``PendingFileRenameOperations``, which antivirus and installers set routinely and which would keep the flag up for days, ``UpdateExeVolatile`` and a new computer name taking effect at the next restart. They make up ``reboot_reason`` with the two above, and a host with only them needs no restart. **Automatic updates** follow the policy (``HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\ WindowsUpdate\\AU``): ``NoAutoUpdate=1`` is off; ``AUOptions`` 4 installs on its own, 2, 3 and 7 only notify or download; 5 leaves it to the local setting. Without a policy Windows 10 and 11 install on their own, and ignore the local ``AUOptions`` an upgrade may have left; a Windows Server follows its local setting (``sconfig``), and without one the answer is None: what each Server release does then is not established. **When they last succeeded** is the latest successful installation Windows Update knows of, whoever started it: its history's last 50 entries, the ``Microsoft.Update.AutoUpdate`` result and the older registry result (``Auto Update\\Results\\Install``), whichever is latest. Windows has something to install every month -- the cumulative update -- so automatic updates are meant to have installed something within 31 days (``auto_updates_interval``); on Linux that is the timer's day. **Filesystems** are the system drive's size and free space, where updates unpack. """ from __future__ import annotations import calendar import time from typing import TYPE_CHECKING, Any from napalm_device_types.models import FilesystemUsageDict, HostStatusDict from napalm_windows._powershell import _as_list from napalm_windows._reading import json_object _AU_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" _AU_LOCAL = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" _CBS = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing" _SESSION_MANAGER = r"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" _COMPUTER_NAME = r"HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName" # WUA's dates are UTC with no kind; IUpdateHistoryEntry.Operation 1 is an installation, # ResultCode 2 succeeded and 3 succeeded with errors. _PS_HOST_STATUS = rf""" $ErrorActionPreference = 'Stop' function V($path, $name) {{ $item = Get-ItemProperty -LiteralPath $path -Name $name -ErrorAction SilentlyContinue if ($item) {{ $item.$name }} }} function Utc($t) {{ if ($t) {{ ([DateTimeOffset][DateTime]::SpecifyKind($t, 'Utc')).ToUnixTimeSeconds() }} }} $wu = $null try {{ $wu = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired }} catch {{ }} $installs = $null try {{ $searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher() $count = $searcher.GetTotalHistoryCount() $installs = @(if ($count -gt 0) {{ $searcher.QueryHistory(0, [Math]::Min($count, 50)) | Where-Object {{ $_.Operation -eq 1 -and ($_.ResultCode -eq 2 -or $_.ResultCode -eq 3) }} | ForEach-Object {{ Utc $_.Date }} }}) }} catch {{ }} $au = $null try {{ $results = (New-Object -ComObject Microsoft.Update.AutoUpdate).Results $au = Utc $results.LastInstallationSuccessDate }} catch {{ }} $drive = $null try {{ $disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'" if ($disk) {{ $drive = [pscustomobject]@{{ drive = [string]$disk.DeviceID; size = [int64]$disk.Size; free = [int64]$disk.FreeSpace }} }} }} catch {{ }} ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{{ wu_reboot_required = $wu cbs_reboot_pending = Test-Path -LiteralPath '{_CBS}\RebootPending' wu_reboot_key = Test-Path -LiteralPath '{_AU_LOCAL}\RebootRequired' file_renames = [bool](V '{_SESSION_MANAGER}' 'PendingFileRenameOperations') update_exe = [string](V 'HKLM:\SOFTWARE\Microsoft\Updates' 'UpdateExeVolatile') computer_name = [string](V '{_COMPUTER_NAME}\ComputerName' 'ComputerName') active_name = [string](V '{_COMPUTER_NAME}\ActiveComputerName' 'ComputerName') no_auto_update = [string](V '{_AU_POLICY}' 'NoAutoUpdate') au_options = [string](V '{_AU_POLICY}' 'AUOptions') local_au_options = [string](V '{_AU_LOCAL}' 'AUOptions') product_type = [int](Get-CimInstance -ClassName Win32_OperatingSystem).ProductType installs = $installs au_last_install = $au legacy_last_install = [string](V '{_AU_LOCAL}\Results\Install' 'LastSuccessTime') system_drive = $drive }}) """ #: ``AUOptions``: 2 notify, 3 download and notify, 4 install on a schedule, 7 (Server) #: download, notify to install and to restart; 1 is the older "never check". _AU_OPTIONS = {"1": False, "2": False, "3": False, "4": True, "7": False} #: ``Win32_OperatingSystem.ProductType`` of a client; 2 and 3 are servers. _WORKSTATION = 1 #: How often a Windows host has something to install: the monthly cumulative update. MONTHLY = 31 * 86400 def _marker(raw: dict[str, Any], key: str) -> bool: return raw.get(key) is True #: The markers that explain a restart, in the order they are named, each with its words. _REASONS = ( ( ("wu_reboot_required", "wu_reboot_key"), "Windows Update needs a restart to finish installing updates", ), (("cbs_reboot_pending",), "component-based servicing has a restart pending"), ( ("file_renames",), "files wait to be replaced at the next restart (PendingFileRenameOperations)", ), ) def _rename(raw: dict[str, Any]) -> str | None: """The new computer name a restart takes effect with, if there is one.""" new, active = str(raw.get("computer_name") or ""), str(raw.get("active_name") or "") if new and active and new.lower() != active.lower(): return f"the computer takes its new name {new} at the next restart" return None def _restart_reasons(raw: dict[str, Any]) -> list[str]: reasons = [text for keys, text in _REASONS if any(_marker(raw, key) for key in keys)] if str(raw.get("update_exe") or "0") != "0": reasons.append("an update waits for a restart (UpdateExeVolatile)") rename = _rename(raw) return [*reasons, rename] if rename else reasons def _restart_required(raw: dict[str, Any]) -> bool: """Windows Update or component servicing waits for a restart; see the module.""" return any( _marker(raw, key) for key in ("wu_reboot_required", "wu_reboot_key", "cbs_reboot_pending") ) def _auto_updates(raw: dict[str, Any]) -> bool | None: """Whether the host installs updates on its own; see the module.""" if str(raw.get("no_auto_update") or "") == "1": return False policy = _AU_OPTIONS.get(str(raw.get("au_options") or "")) if policy is not None: return policy if int(raw.get("product_type") or 0) == _WORKSTATION: return True return _AU_OPTIONS.get(str(raw.get("local_au_options") or "")) def _registry_time(value: Any) -> int | None: """``Results\\Install``'s ``LastSuccessTime``, ``YYYY-MM-DD HH:MM:SS`` in UTC.""" try: return calendar.timegm(time.strptime(str(value or ""), "%Y-%m-%d %H:%M:%S")) except ValueError: return None def _last_success(raw: dict[str, Any]) -> int | None: """The latest successful installation any of the three sources knows of.""" known = [*_as_list(raw.get("installs")), raw.get("au_last_install")] known.append(_registry_time(raw.get("legacy_last_install"))) times = [int(t) for t in known if isinstance(t, int | float) and t > 0] return max(times, default=None) def _filesystems(raw: dict[str, Any]) -> list[FilesystemUsageDict] | None: drive = raw.get("system_drive") if not isinstance(drive, dict): return None total, free = int(drive.get("size") or 0), int(drive.get("free") or 0) return [ { "mountpoint": f"{drive.get('drive') or ''}\\", "total": total, "used": total - free, "available": free, } ] def parse_host_status(raw: dict[str, Any]) -> HostStatusDict: """``_PS_HOST_STATUS``'s JSON as the host status; see the module.""" reasons = _restart_reasons(raw) auto = _auto_updates(raw) return { "reboot_required": _restart_required(raw), "reboot_reason": "; ".join(reasons) or None, "auto_updates": auto, "auto_updates_last_success": _last_success(raw), "auto_updates_interval": MONTHLY if auto else None, "filesystems": _filesystems(raw), } class WindowsHostStatusMixin: """``get_host_status`` from Windows Update and the registry; the driver carries the script.""" if TYPE_CHECKING: # pragma: no cover - declared for type checkers only def _run_raw(self, script: str) -> str: ... def get_host_status(self) -> HostStatusDict: """Whether the host needs a restart and installs updates on its own; see the module. :raises ValueError: when the reading came back empty. """ return parse_host_status(json_object(self._run_raw(_PS_HOST_STATUS), "host status"))