"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889). :class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes`` (``ProcessDict``). One script reads two sources and the join happens here: * ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time (``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and ``VirtualSize``. Read first: it is the list. * ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a ``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM administrator has; without one the script falls back to ``Get-Process`` and the owner is unknown (empty). A process is reported only when both saw it with the same start: one that exited between the two reads is dropped rather than half-filled, and a PID reused in between is another process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves it out. The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per logical processor, so 0-100; ``memory`` the working set over the visible memory; ``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local time. Windows has no controlling terminal and no process state of that kind: ``tty`` and ``state`` are empty. A process without a readable command line (``System``, protected processes) shows its image name. Command lines are reported as the host gives them, as ``ps`` does on Linux. """ from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any from napalm_device_types.models import ProcessDict from napalm_windows._powershell import _as_list from napalm_windows._reading import json_object _PS_PROCESSES = r""" $ErrorActionPreference = 'Stop' function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } } function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } } $os = Get-CimInstance -ClassName Win32_OperatingSystem $cs = Get-CimInstance -ClassName Win32_ComputerSystem $processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object { [pscustomobject]@{ pid = [int]$_.ProcessId ppid = [int]$_.ParentProcessId name = [string]$_.Name command = [string]$_.CommandLine started = Unix $_.CreationDate offset = Offset $_.CreationDate cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime ws = [int64]$_.WorkingSetSize vsz = [int64]$_.VirtualSize } }) try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) } $owners = @($running | ForEach-Object { $start = $null try { $start = Unix $_.StartTime } catch { } [pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start } }) ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{ now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() cores = [int]$cs.NumberOfLogicalProcessors memory_kib = [int64]$os.TotalVisibleMemorySize processes = $processes owners = $owners }) """ #: How far the two sources' starts of one process may differ: they round differently. _SAME_START = 2 _DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") def _lstart(started: int | None, offset_minutes: int) -> str: """Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale.""" if started is None: return "" t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes) return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}" class _Host: """What the reading says about the host as a whole.""" def __init__(self, raw: dict[str, Any]) -> None: self.now = int(raw.get("now") or 0) self.cores = max(int(raw.get("cores") or 1), 1) self.memory_kib = int(raw.get("memory_kib") or 0) def cpu(self, cpu_100ns: int, started: int | None) -> float: if started is None: return 0.0 elapsed = max(self.now - started, 1) return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1) def memory(self, rss_kib: int) -> float: return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0 def _started(entry: dict[str, Any]) -> int | None: value = entry.get("started") return int(value) if value is not None else None def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool: """False when ``Get-Process`` saw another start under this PID: it was reused.""" ours, theirs = _started(entry), _started(owner) return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict: started = _started(entry) rss = int(entry.get("ws") or 0) // 1024 return { "pid": int(entry["pid"]), "ppid": int(entry.get("ppid") or 0), "user": str(owner.get("user") or ""), "cpu": host.cpu(int(entry.get("cpu") or 0), started), "memory": host.memory(rss), "vsz": int(entry.get("vsz") or 0) // 1024, "rss": rss, "tty": "", "state": "", "started": _lstart(started, int(entry.get("offset") or 0)), "command": str(entry.get("command") or entry.get("name") or ""), } def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]: """``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join.""" host = _Host(raw) owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))} processes = [] for entry in _as_list(raw.get("processes")): owner = owners.get(int(entry["pid"])) if not entry["pid"] or owner is None or not _same_process(entry, owner): continue processes.append(_process(entry, owner, host)) return sorted(processes, key=lambda p: p["pid"]) class WindowsProcessesMixin: """``get_processes`` from ``Win32_Process`` and ``Get-Process``; 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_processes(self) -> list[ProcessDict]: """A snapshot of the running processes, shaped like ``ps``; see the module. :raises ValueError: when the reading came back empty. """ return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process"))