Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a5c607ae4 | ||
|
|
977ddbd904 | ||
|
|
d7511efd43 | ||
|
|
442541d30a | ||
|
|
0b30ab00a5 | ||
|
|
37708009a0 | ||
|
|
74a8c53c7c | ||
|
|
a508b872b0 | ||
|
|
581c2df5e8 | ||
|
|
dacefaa606 | ||
|
|
7c985acfad | ||
|
|
cd50d3c102 | ||
|
|
15740f9e05 |
No files matched your search
@@ -6,6 +6,69 @@ 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.
|
||||
- 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
|
||||
`-Force`: Windows asks running programs to close and refuses while other users are
|
||||
logged on, a disconnected session included, instead of throwing away what they have
|
||||
not saved. A refusal raises `RuntimeError` with the host's answer. Both cmdlets start
|
||||
the shutdown and return, so no delay is needed before the session goes; a connection
|
||||
the host drops before answering counts as accepted. `PsrpTransport.run_last(script)`
|
||||
tells the two apart: `False` when the connection broke, `PowerShellError` when the
|
||||
script wrote an error.
|
||||
- Time sync: napalm-device-types' `TimeSyncMixin` (4.35.0), servers and zone
|
||||
(NetOrk/netork#2367). `get_time_sync` reads w32time's `NtpServer` and `Type` from the
|
||||
registry (group policy's first; `NoSync` has no servers), whether the clock is
|
||||
synchronised (the leap indicator of `w32tm /query /status`) and the zone, in one
|
||||
script. `configure_time_sync` writes the servers as `<server>,0x8` with `Type NTP`
|
||||
and `w32tm /config /update`, starting a stopped Windows Time service, and the zone
|
||||
with `Set-TimeZone`. A domain member that takes its time from the domain hierarchy
|
||||
(`NT5DS`, `AllSync`) reports its configured servers and refuses the write, as does a
|
||||
host whose w32time settings come from group policy. The IANA name written is kept in
|
||||
`HKLM\SOFTWARE\napalm-windows` so it reads back as written; writes the host already
|
||||
has are skipped.
|
||||
- The time zone table is CLDR's `windowsZones.xml` (release 49), generated into
|
||||
`napalm_windows/_windows_zones.py` by `tools/windows_zones.py` with tzdata's links,
|
||||
both ways: every Windows zone reads as an IANA name, not only the common ones, and
|
||||
every IANA zone CLDR maps has its Windows zone.
|
||||
- Scheduled jobs: the Task Scheduler as napalm-device-types' `ScheduledJobsMixin` (#8).
|
||||
`get_scheduled_jobs` reads every task with its last and next run in one script
|
||||
(`Get-ScheduledTask`, `Get-ScheduledTaskInfo`) as `task:<path><name>`: a task under
|
||||
`\Microsoft\` is the `platform`'s, any other the `admin`'s, and a task in the root
|
||||
folder whose description starts with `napalm-scheduled-job: <name>` an `application`'s.
|
||||
The time zone comes as an IANA name for the common Windows zones, else `None`.
|
||||
`manage_scheduled_job` enables, disables (`Enable-`/`Disable-ScheduledTask`) or starts
|
||||
one (`Start-ScheduledTask`, which returns once the task has started). `put_scheduled_job`
|
||||
registers an application's task `\<name>` from XML: the command runs in
|
||||
`cmd.exe /d /s /c`, `SYSTEM` or a local user without a stored password (S4U), and the
|
||||
cron expression becomes triggers where Task Scheduler can express it exactly; any other
|
||||
shape is refused, naming why. `delete_scheduled_job` unregisters it. Every write reads
|
||||
the task again first and refuses over a change it did not see. Fixture synthetic.
|
||||
|
||||
### Changed
|
||||
- The floor on napalm-device-types is 4.35.0, which declares the time sync contract.
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||
3.12 venv no longer has.
|
||||
|
||||
### Fixed
|
||||
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
|
||||
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now":
|
||||
`Get-NetNeighbor` has a state but no age (NetOrk/netork#1327).
|
||||
|
||||
## [0.2.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI.
|
||||
|
||||
@@ -37,13 +37,95 @@ handshake once.
|
||||
| `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` |
|
||||
| `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_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
|
||||
matching has to compare against.
|
||||
|
||||
Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V.
|
||||
### Scheduled tasks
|
||||
|
||||
An application's own job is the task `\<name>` in the root folder, never a folder of
|
||||
its own. Its description is `napalm-scheduled-job: <name> <description>` and a second
|
||||
line `schedule: <cron expression>`, so the reading gives back the cron expression and
|
||||
the command it was written with; its digest also covers the triggers, so triggers
|
||||
changed by hand count as a change.
|
||||
|
||||
* **Command:** `cmd.exe /d /s /c "<command>"` — one line, as a Windows command line.
|
||||
* **Principal:** `SYSTEM`, or a local user who runs it whether logged on or not
|
||||
without a stored password (`S4U`). Such a run has no network credentials, and the
|
||||
user needs the "Log on as a batch job" right.
|
||||
* **Schedule:** a cron expression becomes triggers only where Task Scheduler can
|
||||
express it exactly — daily, weekly on weekdays, or monthly on days of the month (in
|
||||
some months); at one or more times, or evenly spaced times as one repetition
|
||||
(`*/5`, `*/15 8-17`, `0 */6`), or one repeating trigger per hour (`*/7`); at most 48
|
||||
triggers. `@reboot` is a boot trigger. Refused, naming why: both a day of the month
|
||||
and a weekday (cron's *either* rule), a weekday together with days or months, and
|
||||
times needing more than 48 triggers. A repetition counts elapsed time, so on the day
|
||||
summer time starts or ends its later runs shift by the hour.
|
||||
* **Not read:** which software installed a task (Windows does not record it), so a
|
||||
vendor's updater is `admin`; and the days of a monthly trigger, which
|
||||
`Get-ScheduledTask` does not expose.
|
||||
|
||||
### Time sync
|
||||
|
||||
napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
|
||||
|
||||
* **Servers** are w32time's `NtpServer` in order, without their `,0x` flags; group
|
||||
policy's values (`HKLM\SOFTWARE\Policies\Microsoft\W32Time\Parameters`) win over
|
||||
the local ones. `Type NoSync` has none. Written as `<server>,0x8` (client mode) with
|
||||
`Type NTP` — what `w32tm /config /manualpeerlist /syncfromflags:manual` writes —
|
||||
then `w32tm /config /update`; a stopped Windows Time service is started first.
|
||||
* **Domain members** that take their time from the domain hierarchy (`Type NT5DS` or
|
||||
`AllSync`) report the servers configured, and a write is refused: the domain sets
|
||||
their time. So is a write where group policy sets w32time.
|
||||
* **Synchronised** is the leap indicator of `w32tm /query /status` (`3` = not
|
||||
synchronised); a stopped service is not synchronised. `daemon` is `w32time`.
|
||||
* **Zone:** Windows keeps a Windows zone (`W. Europe Standard Time`), which stands
|
||||
for several IANA zones. It is read as the zone CLDR names for it (`Europe/Berlin`)
|
||||
and written with `Set-TimeZone` from CLDR's mapping
|
||||
([`windowsZones.xml`](https://github.com/unicode-org/cldr/blob/release-49/common/supplemental/windowsZones.xml),
|
||||
generated into `napalm_windows/_windows_zones.py` by `tools/windows_zones.py`,
|
||||
never fetched at runtime). The IANA name written is kept in
|
||||
`HKLM\SOFTWARE\napalm-windows` (`IanaTimeZone`) and read back while the host is
|
||||
still in that Windows zone, so `Europe/Vienna` reads back as `Europe/Vienna`. A
|
||||
zone with summer time switched off reads as `None`; writing the zone switches it
|
||||
back on.
|
||||
|
||||
### Storage
|
||||
|
||||
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.
|
||||
|
||||
* **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.
|
||||
|
||||
A host without the Storage module reads as having none; an empty answer raises.
|
||||
|
||||
Not yet: packages, Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
## Preparing a host
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""What every script and every parse of this driver shares: quoting and the JSON quirk."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# PowerShell accepts these as single-quote delimiters alongside the ASCII one.
|
||||
_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛")
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[Any]:
|
||||
"""Undo ConvertTo-Json unwrapping a one-element array into a bare value."""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
return [value]
|
||||
|
||||
|
||||
def _ps_quote(value: str) -> str:
|
||||
"""Quote ``value`` as a PowerShell single-quoted (verbatim) string."""
|
||||
for q in _PS_SINGLE_QUOTES:
|
||||
value = value.replace(q, q + q)
|
||||
return f"'{value}'"
|
||||
@@ -0,0 +1,732 @@
|
||||
"""Windows time zones and IANA names. Generated by tools/windows_zones.py: do not edit.
|
||||
|
||||
Source: CLDR release-49, common/supplemental/windowsZones.xml
|
||||
(sha256 5f902f94106a396cb7774f0b0e1ca4dfecb686494045350c0b4935d378e3913b),
|
||||
with the link lines of the IANA time zone database 2026e (tzdata.zi).
|
||||
"""
|
||||
|
||||
WINDOWS_TO_IANA: dict[str, str] = {
|
||||
"AUS Central Standard Time": "Australia/Darwin",
|
||||
"AUS Eastern Standard Time": "Australia/Sydney",
|
||||
"Afghanistan Standard Time": "Asia/Kabul",
|
||||
"Alaskan Standard Time": "America/Anchorage",
|
||||
"Alberta Standard Time": "America/Edmonton",
|
||||
"Aleutian Standard Time": "America/Adak",
|
||||
"Altai Standard Time": "Asia/Barnaul",
|
||||
"Arab Standard Time": "Asia/Riyadh",
|
||||
"Arabian Standard Time": "Asia/Dubai",
|
||||
"Arabic Standard Time": "Asia/Baghdad",
|
||||
"Argentina Standard Time": "America/Argentina/Buenos_Aires",
|
||||
"Astrakhan Standard Time": "Europe/Astrakhan",
|
||||
"Atlantic Standard Time": "America/Halifax",
|
||||
"Aus Central W. Standard Time": "Australia/Eucla",
|
||||
"Azerbaijan Standard Time": "Asia/Baku",
|
||||
"Azores Standard Time": "Atlantic/Azores",
|
||||
"Bahia Standard Time": "America/Bahia",
|
||||
"Bangladesh Standard Time": "Asia/Dhaka",
|
||||
"Belarus Standard Time": "Europe/Minsk",
|
||||
"Bougainville Standard Time": "Pacific/Bougainville",
|
||||
"British Columbia Standard Time": "America/Vancouver",
|
||||
"Canada Central Standard Time": "America/Regina",
|
||||
"Cape Verde Standard Time": "Atlantic/Cape_Verde",
|
||||
"Caucasus Standard Time": "Asia/Yerevan",
|
||||
"Cen. Australia Standard Time": "Australia/Adelaide",
|
||||
"Central America Standard Time": "America/Guatemala",
|
||||
"Central Asia Standard Time": "Asia/Bishkek",
|
||||
"Central Brazilian Standard Time": "America/Cuiaba",
|
||||
"Central Europe Standard Time": "Europe/Budapest",
|
||||
"Central European Standard Time": "Europe/Warsaw",
|
||||
"Central Pacific Standard Time": "Pacific/Guadalcanal",
|
||||
"Central Standard Time": "America/Chicago",
|
||||
"Central Standard Time (Mexico)": "America/Mexico_City",
|
||||
"Chatham Islands Standard Time": "Pacific/Chatham",
|
||||
"China Standard Time": "Asia/Shanghai",
|
||||
"Cuba Standard Time": "America/Havana",
|
||||
"Dateline Standard Time": "Etc/GMT+12",
|
||||
"E. Africa Standard Time": "Africa/Nairobi",
|
||||
"E. Australia Standard Time": "Australia/Brisbane",
|
||||
"E. Europe Standard Time": "Europe/Chisinau",
|
||||
"E. South America Standard Time": "America/Sao_Paulo",
|
||||
"Easter Island Standard Time": "Pacific/Easter",
|
||||
"Eastern Standard Time": "America/New_York",
|
||||
"Eastern Standard Time (Mexico)": "America/Cancun",
|
||||
"Egypt Standard Time": "Africa/Cairo",
|
||||
"Ekaterinburg Standard Time": "Asia/Yekaterinburg",
|
||||
"FLE Standard Time": "Europe/Kyiv",
|
||||
"Fiji Standard Time": "Pacific/Fiji",
|
||||
"GMT Standard Time": "Europe/London",
|
||||
"GTB Standard Time": "Europe/Bucharest",
|
||||
"Georgian Standard Time": "Asia/Tbilisi",
|
||||
"Greenland Standard Time": "America/Nuuk",
|
||||
"Greenwich Standard Time": "Atlantic/Reykjavik",
|
||||
"Haiti Standard Time": "America/Port-au-Prince",
|
||||
"Hawaiian Standard Time": "Pacific/Honolulu",
|
||||
"India Standard Time": "Asia/Kolkata",
|
||||
"Iran Standard Time": "Asia/Tehran",
|
||||
"Israel Standard Time": "Asia/Jerusalem",
|
||||
"Jordan Standard Time": "Asia/Amman",
|
||||
"Kaliningrad Standard Time": "Europe/Kaliningrad",
|
||||
"Korea Standard Time": "Asia/Seoul",
|
||||
"Libya Standard Time": "Africa/Tripoli",
|
||||
"Line Islands Standard Time": "Pacific/Kiritimati",
|
||||
"Lord Howe Standard Time": "Australia/Lord_Howe",
|
||||
"Magadan Standard Time": "Asia/Magadan",
|
||||
"Magallanes Standard Time": "America/Punta_Arenas",
|
||||
"Manitoba Standard Time": "America/Winnipeg",
|
||||
"Marquesas Standard Time": "Pacific/Marquesas",
|
||||
"Mauritius Standard Time": "Indian/Mauritius",
|
||||
"Middle East Standard Time": "Asia/Beirut",
|
||||
"Montevideo Standard Time": "America/Montevideo",
|
||||
"Morocco Standard Time": "Africa/Casablanca",
|
||||
"Mountain Standard Time": "America/Denver",
|
||||
"Mountain Standard Time (Mexico)": "America/Mazatlan",
|
||||
"Myanmar Standard Time": "Asia/Yangon",
|
||||
"N. Central Asia Standard Time": "Asia/Novosibirsk",
|
||||
"Namibia Standard Time": "Africa/Windhoek",
|
||||
"Nepal Standard Time": "Asia/Kathmandu",
|
||||
"New Zealand Standard Time": "Pacific/Auckland",
|
||||
"Newfoundland Standard Time": "America/St_Johns",
|
||||
"Norfolk Standard Time": "Pacific/Norfolk",
|
||||
"North Asia East Standard Time": "Asia/Irkutsk",
|
||||
"North Asia Standard Time": "Asia/Krasnoyarsk",
|
||||
"North Korea Standard Time": "Asia/Pyongyang",
|
||||
"Omsk Standard Time": "Asia/Omsk",
|
||||
"Pacific SA Standard Time": "America/Santiago",
|
||||
"Pacific Standard Time": "America/Los_Angeles",
|
||||
"Pacific Standard Time (Mexico)": "America/Tijuana",
|
||||
"Pakistan Standard Time": "Asia/Karachi",
|
||||
"Paraguay Standard Time": "America/Asuncion",
|
||||
"Qyzylorda Standard Time": "Asia/Qyzylorda",
|
||||
"Romance Standard Time": "Europe/Paris",
|
||||
"Russia Time Zone 10": "Asia/Srednekolymsk",
|
||||
"Russia Time Zone 11": "Asia/Kamchatka",
|
||||
"Russia Time Zone 3": "Europe/Samara",
|
||||
"Russian Standard Time": "Europe/Moscow",
|
||||
"SA Eastern Standard Time": "America/Cayenne",
|
||||
"SA Pacific Standard Time": "America/Bogota",
|
||||
"SA Western Standard Time": "America/La_Paz",
|
||||
"SE Asia Standard Time": "Asia/Bangkok",
|
||||
"Saint Pierre Standard Time": "America/Miquelon",
|
||||
"Sakhalin Standard Time": "Asia/Sakhalin",
|
||||
"Samoa Standard Time": "Pacific/Apia",
|
||||
"Sao Tome Standard Time": "Africa/Sao_Tome",
|
||||
"Saratov Standard Time": "Europe/Saratov",
|
||||
"Singapore Standard Time": "Asia/Singapore",
|
||||
"South Africa Standard Time": "Africa/Johannesburg",
|
||||
"South Sudan Standard Time": "Africa/Juba",
|
||||
"Sri Lanka Standard Time": "Asia/Colombo",
|
||||
"Sudan Standard Time": "Africa/Khartoum",
|
||||
"Syria Standard Time": "Asia/Damascus",
|
||||
"Taipei Standard Time": "Asia/Taipei",
|
||||
"Tasmania Standard Time": "Australia/Hobart",
|
||||
"Tocantins Standard Time": "America/Araguaina",
|
||||
"Tokyo Standard Time": "Asia/Tokyo",
|
||||
"Tomsk Standard Time": "Asia/Tomsk",
|
||||
"Tonga Standard Time": "Pacific/Tongatapu",
|
||||
"Transbaikal Standard Time": "Asia/Chita",
|
||||
"Turkey Standard Time": "Europe/Istanbul",
|
||||
"Turks And Caicos Standard Time": "America/Grand_Turk",
|
||||
"US Eastern Standard Time": "America/Indiana/Indianapolis",
|
||||
"US Mountain Standard Time": "America/Phoenix",
|
||||
"UTC": "Etc/UTC",
|
||||
"UTC+12": "Etc/GMT-12",
|
||||
"UTC+13": "Etc/GMT-13",
|
||||
"UTC-02": "Etc/GMT+2",
|
||||
"UTC-08": "Etc/GMT+8",
|
||||
"UTC-09": "Etc/GMT+9",
|
||||
"UTC-11": "Etc/GMT+11",
|
||||
"Ulaanbaatar Standard Time": "Asia/Ulaanbaatar",
|
||||
"Venezuela Standard Time": "America/Caracas",
|
||||
"Vladivostok Standard Time": "Asia/Vladivostok",
|
||||
"Volgograd Standard Time": "Europe/Volgograd",
|
||||
"W. Australia Standard Time": "Australia/Perth",
|
||||
"W. Central Africa Standard Time": "Africa/Lagos",
|
||||
"W. Europe Standard Time": "Europe/Berlin",
|
||||
"W. Mongolia Standard Time": "Asia/Hovd",
|
||||
"West Asia Standard Time": "Asia/Tashkent",
|
||||
"West Bank Standard Time": "Asia/Hebron",
|
||||
"West Pacific Standard Time": "Pacific/Port_Moresby",
|
||||
"Yakutsk Standard Time": "Asia/Yakutsk",
|
||||
"Yukon Standard Time": "America/Whitehorse",
|
||||
}
|
||||
|
||||
IANA_TO_WINDOWS: dict[str, str] = {
|
||||
"Africa/Abidjan": "Greenwich Standard Time",
|
||||
"Africa/Accra": "Greenwich Standard Time",
|
||||
"Africa/Addis_Ababa": "E. Africa Standard Time",
|
||||
"Africa/Algiers": "W. Central Africa Standard Time",
|
||||
"Africa/Asmara": "E. Africa Standard Time",
|
||||
"Africa/Asmera": "E. Africa Standard Time",
|
||||
"Africa/Bamako": "Greenwich Standard Time",
|
||||
"Africa/Bangui": "W. Central Africa Standard Time",
|
||||
"Africa/Banjul": "Greenwich Standard Time",
|
||||
"Africa/Bissau": "Greenwich Standard Time",
|
||||
"Africa/Blantyre": "South Africa Standard Time",
|
||||
"Africa/Brazzaville": "W. Central Africa Standard Time",
|
||||
"Africa/Bujumbura": "South Africa Standard Time",
|
||||
"Africa/Cairo": "Egypt Standard Time",
|
||||
"Africa/Casablanca": "Morocco Standard Time",
|
||||
"Africa/Ceuta": "Romance Standard Time",
|
||||
"Africa/Conakry": "Greenwich Standard Time",
|
||||
"Africa/Dakar": "Greenwich Standard Time",
|
||||
"Africa/Dar_es_Salaam": "E. Africa Standard Time",
|
||||
"Africa/Djibouti": "E. Africa Standard Time",
|
||||
"Africa/Douala": "W. Central Africa Standard Time",
|
||||
"Africa/El_Aaiun": "Morocco Standard Time",
|
||||
"Africa/Freetown": "Greenwich Standard Time",
|
||||
"Africa/Gaborone": "South Africa Standard Time",
|
||||
"Africa/Harare": "South Africa Standard Time",
|
||||
"Africa/Johannesburg": "South Africa Standard Time",
|
||||
"Africa/Juba": "South Sudan Standard Time",
|
||||
"Africa/Kampala": "E. Africa Standard Time",
|
||||
"Africa/Khartoum": "Sudan Standard Time",
|
||||
"Africa/Kigali": "South Africa Standard Time",
|
||||
"Africa/Kinshasa": "W. Central Africa Standard Time",
|
||||
"Africa/Lagos": "W. Central Africa Standard Time",
|
||||
"Africa/Libreville": "W. Central Africa Standard Time",
|
||||
"Africa/Lome": "Greenwich Standard Time",
|
||||
"Africa/Luanda": "W. Central Africa Standard Time",
|
||||
"Africa/Lubumbashi": "South Africa Standard Time",
|
||||
"Africa/Lusaka": "South Africa Standard Time",
|
||||
"Africa/Malabo": "W. Central Africa Standard Time",
|
||||
"Africa/Maputo": "South Africa Standard Time",
|
||||
"Africa/Maseru": "South Africa Standard Time",
|
||||
"Africa/Mbabane": "South Africa Standard Time",
|
||||
"Africa/Mogadishu": "E. Africa Standard Time",
|
||||
"Africa/Monrovia": "Greenwich Standard Time",
|
||||
"Africa/Nairobi": "E. Africa Standard Time",
|
||||
"Africa/Ndjamena": "W. Central Africa Standard Time",
|
||||
"Africa/Niamey": "W. Central Africa Standard Time",
|
||||
"Africa/Nouakchott": "Greenwich Standard Time",
|
||||
"Africa/Ouagadougou": "Greenwich Standard Time",
|
||||
"Africa/Porto-Novo": "W. Central Africa Standard Time",
|
||||
"Africa/Sao_Tome": "Sao Tome Standard Time",
|
||||
"Africa/Timbuktu": "Greenwich Standard Time",
|
||||
"Africa/Tripoli": "Libya Standard Time",
|
||||
"Africa/Tunis": "W. Central Africa Standard Time",
|
||||
"Africa/Windhoek": "Namibia Standard Time",
|
||||
"America/Adak": "Aleutian Standard Time",
|
||||
"America/Anchorage": "Alaskan Standard Time",
|
||||
"America/Anguilla": "SA Western Standard Time",
|
||||
"America/Antigua": "SA Western Standard Time",
|
||||
"America/Araguaina": "Tocantins Standard Time",
|
||||
"America/Argentina/Buenos_Aires": "Argentina Standard Time",
|
||||
"America/Argentina/Catamarca": "Argentina Standard Time",
|
||||
"America/Argentina/Cordoba": "Argentina Standard Time",
|
||||
"America/Argentina/Jujuy": "Argentina Standard Time",
|
||||
"America/Argentina/La_Rioja": "Argentina Standard Time",
|
||||
"America/Argentina/Mendoza": "Argentina Standard Time",
|
||||
"America/Argentina/Rio_Gallegos": "Argentina Standard Time",
|
||||
"America/Argentina/Salta": "Argentina Standard Time",
|
||||
"America/Argentina/San_Juan": "Argentina Standard Time",
|
||||
"America/Argentina/San_Luis": "Argentina Standard Time",
|
||||
"America/Argentina/Tucuman": "Argentina Standard Time",
|
||||
"America/Argentina/Ushuaia": "Argentina Standard Time",
|
||||
"America/Aruba": "SA Western Standard Time",
|
||||
"America/Asuncion": "Paraguay Standard Time",
|
||||
"America/Atikokan": "SA Pacific Standard Time",
|
||||
"America/Atka": "Aleutian Standard Time",
|
||||
"America/Bahia": "Bahia Standard Time",
|
||||
"America/Bahia_Banderas": "Central Standard Time (Mexico)",
|
||||
"America/Barbados": "SA Western Standard Time",
|
||||
"America/Belem": "SA Eastern Standard Time",
|
||||
"America/Belize": "Central America Standard Time",
|
||||
"America/Blanc-Sablon": "SA Western Standard Time",
|
||||
"America/Boa_Vista": "SA Western Standard Time",
|
||||
"America/Bogota": "SA Pacific Standard Time",
|
||||
"America/Boise": "Mountain Standard Time",
|
||||
"America/Buenos_Aires": "Argentina Standard Time",
|
||||
"America/Cambridge_Bay": "Mountain Standard Time",
|
||||
"America/Campo_Grande": "Central Brazilian Standard Time",
|
||||
"America/Cancun": "Eastern Standard Time (Mexico)",
|
||||
"America/Caracas": "Venezuela Standard Time",
|
||||
"America/Catamarca": "Argentina Standard Time",
|
||||
"America/Cayenne": "SA Eastern Standard Time",
|
||||
"America/Cayman": "SA Pacific Standard Time",
|
||||
"America/Chicago": "Central Standard Time",
|
||||
"America/Chihuahua": "Central Standard Time (Mexico)",
|
||||
"America/Ciudad_Juarez": "Mountain Standard Time",
|
||||
"America/Coral_Harbour": "SA Pacific Standard Time",
|
||||
"America/Cordoba": "Argentina Standard Time",
|
||||
"America/Costa_Rica": "Central America Standard Time",
|
||||
"America/Coyhaique": "Magallanes Standard Time",
|
||||
"America/Creston": "US Mountain Standard Time",
|
||||
"America/Cuiaba": "Central Brazilian Standard Time",
|
||||
"America/Curacao": "SA Western Standard Time",
|
||||
"America/Danmarkshavn": "Greenwich Standard Time",
|
||||
"America/Dawson": "Yukon Standard Time",
|
||||
"America/Dawson_Creek": "US Mountain Standard Time",
|
||||
"America/Denver": "Mountain Standard Time",
|
||||
"America/Detroit": "Eastern Standard Time",
|
||||
"America/Dominica": "SA Western Standard Time",
|
||||
"America/Edmonton": "Alberta Standard Time",
|
||||
"America/Eirunepe": "SA Pacific Standard Time",
|
||||
"America/El_Salvador": "Central America Standard Time",
|
||||
"America/Ensenada": "Pacific Standard Time (Mexico)",
|
||||
"America/Fort_Nelson": "US Mountain Standard Time",
|
||||
"America/Fortaleza": "SA Eastern Standard Time",
|
||||
"America/Glace_Bay": "Atlantic Standard Time",
|
||||
"America/Godthab": "Greenland Standard Time",
|
||||
"America/Goose_Bay": "Atlantic Standard Time",
|
||||
"America/Grand_Turk": "Turks And Caicos Standard Time",
|
||||
"America/Grenada": "SA Western Standard Time",
|
||||
"America/Guadeloupe": "SA Western Standard Time",
|
||||
"America/Guatemala": "Central America Standard Time",
|
||||
"America/Guayaquil": "SA Pacific Standard Time",
|
||||
"America/Guyana": "SA Western Standard Time",
|
||||
"America/Halifax": "Atlantic Standard Time",
|
||||
"America/Havana": "Cuba Standard Time",
|
||||
"America/Hermosillo": "US Mountain Standard Time",
|
||||
"America/Indiana/Indianapolis": "US Eastern Standard Time",
|
||||
"America/Indiana/Knox": "Central Standard Time",
|
||||
"America/Indiana/Marengo": "US Eastern Standard Time",
|
||||
"America/Indiana/Petersburg": "Eastern Standard Time",
|
||||
"America/Indiana/Tell_City": "Central Standard Time",
|
||||
"America/Indiana/Vevay": "US Eastern Standard Time",
|
||||
"America/Indiana/Vincennes": "Eastern Standard Time",
|
||||
"America/Indiana/Winamac": "Eastern Standard Time",
|
||||
"America/Indianapolis": "US Eastern Standard Time",
|
||||
"America/Inuvik": "Alberta Standard Time",
|
||||
"America/Iqaluit": "Eastern Standard Time",
|
||||
"America/Jamaica": "SA Pacific Standard Time",
|
||||
"America/Jujuy": "Argentina Standard Time",
|
||||
"America/Juneau": "Alaskan Standard Time",
|
||||
"America/Kentucky/Louisville": "Eastern Standard Time",
|
||||
"America/Kentucky/Monticello": "Eastern Standard Time",
|
||||
"America/Knox_IN": "Central Standard Time",
|
||||
"America/Kralendijk": "SA Western Standard Time",
|
||||
"America/La_Paz": "SA Western Standard Time",
|
||||
"America/Lima": "SA Pacific Standard Time",
|
||||
"America/Los_Angeles": "Pacific Standard Time",
|
||||
"America/Louisville": "Eastern Standard Time",
|
||||
"America/Lower_Princes": "SA Western Standard Time",
|
||||
"America/Maceio": "SA Eastern Standard Time",
|
||||
"America/Managua": "Central America Standard Time",
|
||||
"America/Manaus": "SA Western Standard Time",
|
||||
"America/Marigot": "SA Western Standard Time",
|
||||
"America/Martinique": "SA Western Standard Time",
|
||||
"America/Matamoros": "Central Standard Time",
|
||||
"America/Mazatlan": "Mountain Standard Time (Mexico)",
|
||||
"America/Mendoza": "Argentina Standard Time",
|
||||
"America/Menominee": "Central Standard Time",
|
||||
"America/Merida": "Central Standard Time (Mexico)",
|
||||
"America/Metlakatla": "Alaskan Standard Time",
|
||||
"America/Mexico_City": "Central Standard Time (Mexico)",
|
||||
"America/Miquelon": "Saint Pierre Standard Time",
|
||||
"America/Moncton": "Atlantic Standard Time",
|
||||
"America/Monterrey": "Central Standard Time (Mexico)",
|
||||
"America/Montevideo": "Montevideo Standard Time",
|
||||
"America/Montreal": "Eastern Standard Time",
|
||||
"America/Montserrat": "SA Western Standard Time",
|
||||
"America/Nassau": "Eastern Standard Time",
|
||||
"America/New_York": "Eastern Standard Time",
|
||||
"America/Nipigon": "Eastern Standard Time",
|
||||
"America/Nome": "Alaskan Standard Time",
|
||||
"America/Noronha": "UTC-02",
|
||||
"America/North_Dakota/Beulah": "Central Standard Time",
|
||||
"America/North_Dakota/Center": "Central Standard Time",
|
||||
"America/North_Dakota/New_Salem": "Central Standard Time",
|
||||
"America/Nuuk": "Greenland Standard Time",
|
||||
"America/Ojinaga": "Central Standard Time",
|
||||
"America/Panama": "SA Pacific Standard Time",
|
||||
"America/Pangnirtung": "Eastern Standard Time",
|
||||
"America/Paramaribo": "SA Eastern Standard Time",
|
||||
"America/Phoenix": "US Mountain Standard Time",
|
||||
"America/Port-au-Prince": "Haiti Standard Time",
|
||||
"America/Port_of_Spain": "SA Western Standard Time",
|
||||
"America/Porto_Acre": "SA Pacific Standard Time",
|
||||
"America/Porto_Velho": "SA Western Standard Time",
|
||||
"America/Puerto_Rico": "SA Western Standard Time",
|
||||
"America/Punta_Arenas": "Magallanes Standard Time",
|
||||
"America/Rainy_River": "Manitoba Standard Time",
|
||||
"America/Rankin_Inlet": "Central Standard Time",
|
||||
"America/Recife": "SA Eastern Standard Time",
|
||||
"America/Regina": "Canada Central Standard Time",
|
||||
"America/Resolute": "Central Standard Time",
|
||||
"America/Rio_Branco": "SA Pacific Standard Time",
|
||||
"America/Santa_Isabel": "Pacific Standard Time (Mexico)",
|
||||
"America/Santarem": "SA Eastern Standard Time",
|
||||
"America/Santiago": "Pacific SA Standard Time",
|
||||
"America/Santo_Domingo": "SA Western Standard Time",
|
||||
"America/Sao_Paulo": "E. South America Standard Time",
|
||||
"America/Scoresbysund": "Azores Standard Time",
|
||||
"America/Shiprock": "Mountain Standard Time",
|
||||
"America/Sitka": "Alaskan Standard Time",
|
||||
"America/St_Barthelemy": "SA Western Standard Time",
|
||||
"America/St_Johns": "Newfoundland Standard Time",
|
||||
"America/St_Kitts": "SA Western Standard Time",
|
||||
"America/St_Lucia": "SA Western Standard Time",
|
||||
"America/St_Thomas": "SA Western Standard Time",
|
||||
"America/St_Vincent": "SA Western Standard Time",
|
||||
"America/Swift_Current": "Canada Central Standard Time",
|
||||
"America/Tegucigalpa": "Central America Standard Time",
|
||||
"America/Thule": "Atlantic Standard Time",
|
||||
"America/Thunder_Bay": "Eastern Standard Time",
|
||||
"America/Tijuana": "Pacific Standard Time (Mexico)",
|
||||
"America/Toronto": "Eastern Standard Time",
|
||||
"America/Tortola": "SA Western Standard Time",
|
||||
"America/Vancouver": "British Columbia Standard Time",
|
||||
"America/Virgin": "SA Western Standard Time",
|
||||
"America/Whitehorse": "Yukon Standard Time",
|
||||
"America/Winnipeg": "Manitoba Standard Time",
|
||||
"America/Yakutat": "Alaskan Standard Time",
|
||||
"America/Yellowknife": "Alberta Standard Time",
|
||||
"Antarctica/Casey": "Central Pacific Standard Time",
|
||||
"Antarctica/Davis": "SE Asia Standard Time",
|
||||
"Antarctica/DumontDUrville": "West Pacific Standard Time",
|
||||
"Antarctica/Macquarie": "Tasmania Standard Time",
|
||||
"Antarctica/Mawson": "West Asia Standard Time",
|
||||
"Antarctica/McMurdo": "New Zealand Standard Time",
|
||||
"Antarctica/Palmer": "SA Eastern Standard Time",
|
||||
"Antarctica/Rothera": "SA Eastern Standard Time",
|
||||
"Antarctica/South_Pole": "New Zealand Standard Time",
|
||||
"Antarctica/Syowa": "E. Africa Standard Time",
|
||||
"Antarctica/Vostok": "Central Asia Standard Time",
|
||||
"Arctic/Longyearbyen": "W. Europe Standard Time",
|
||||
"Asia/Aden": "Arab Standard Time",
|
||||
"Asia/Almaty": "West Asia Standard Time",
|
||||
"Asia/Amman": "Jordan Standard Time",
|
||||
"Asia/Anadyr": "Russia Time Zone 11",
|
||||
"Asia/Aqtau": "West Asia Standard Time",
|
||||
"Asia/Aqtobe": "West Asia Standard Time",
|
||||
"Asia/Ashgabat": "West Asia Standard Time",
|
||||
"Asia/Ashkhabad": "West Asia Standard Time",
|
||||
"Asia/Atyrau": "West Asia Standard Time",
|
||||
"Asia/Baghdad": "Arabic Standard Time",
|
||||
"Asia/Bahrain": "Arab Standard Time",
|
||||
"Asia/Baku": "Azerbaijan Standard Time",
|
||||
"Asia/Bangkok": "SE Asia Standard Time",
|
||||
"Asia/Barnaul": "Altai Standard Time",
|
||||
"Asia/Beirut": "Middle East Standard Time",
|
||||
"Asia/Bishkek": "Central Asia Standard Time",
|
||||
"Asia/Brunei": "Singapore Standard Time",
|
||||
"Asia/Calcutta": "India Standard Time",
|
||||
"Asia/Chita": "Transbaikal Standard Time",
|
||||
"Asia/Choibalsan": "Ulaanbaatar Standard Time",
|
||||
"Asia/Chongqing": "China Standard Time",
|
||||
"Asia/Chungking": "China Standard Time",
|
||||
"Asia/Colombo": "Sri Lanka Standard Time",
|
||||
"Asia/Dacca": "Bangladesh Standard Time",
|
||||
"Asia/Damascus": "Syria Standard Time",
|
||||
"Asia/Dhaka": "Bangladesh Standard Time",
|
||||
"Asia/Dili": "Tokyo Standard Time",
|
||||
"Asia/Dubai": "Arabian Standard Time",
|
||||
"Asia/Dushanbe": "West Asia Standard Time",
|
||||
"Asia/Famagusta": "GTB Standard Time",
|
||||
"Asia/Gaza": "West Bank Standard Time",
|
||||
"Asia/Harbin": "China Standard Time",
|
||||
"Asia/Hebron": "West Bank Standard Time",
|
||||
"Asia/Ho_Chi_Minh": "SE Asia Standard Time",
|
||||
"Asia/Hong_Kong": "China Standard Time",
|
||||
"Asia/Hovd": "W. Mongolia Standard Time",
|
||||
"Asia/Irkutsk": "North Asia East Standard Time",
|
||||
"Asia/Istanbul": "Turkey Standard Time",
|
||||
"Asia/Jakarta": "SE Asia Standard Time",
|
||||
"Asia/Jayapura": "Tokyo Standard Time",
|
||||
"Asia/Jerusalem": "Israel Standard Time",
|
||||
"Asia/Kabul": "Afghanistan Standard Time",
|
||||
"Asia/Kamchatka": "Russia Time Zone 11",
|
||||
"Asia/Karachi": "Pakistan Standard Time",
|
||||
"Asia/Kashgar": "Central Asia Standard Time",
|
||||
"Asia/Kathmandu": "Nepal Standard Time",
|
||||
"Asia/Katmandu": "Nepal Standard Time",
|
||||
"Asia/Khandyga": "Yakutsk Standard Time",
|
||||
"Asia/Kolkata": "India Standard Time",
|
||||
"Asia/Krasnoyarsk": "North Asia Standard Time",
|
||||
"Asia/Kuala_Lumpur": "Singapore Standard Time",
|
||||
"Asia/Kuching": "Singapore Standard Time",
|
||||
"Asia/Kuwait": "Arab Standard Time",
|
||||
"Asia/Macao": "China Standard Time",
|
||||
"Asia/Macau": "China Standard Time",
|
||||
"Asia/Magadan": "Magadan Standard Time",
|
||||
"Asia/Makassar": "Singapore Standard Time",
|
||||
"Asia/Manila": "Singapore Standard Time",
|
||||
"Asia/Muscat": "Arabian Standard Time",
|
||||
"Asia/Nicosia": "GTB Standard Time",
|
||||
"Asia/Novokuznetsk": "North Asia Standard Time",
|
||||
"Asia/Novosibirsk": "N. Central Asia Standard Time",
|
||||
"Asia/Omsk": "Omsk Standard Time",
|
||||
"Asia/Oral": "West Asia Standard Time",
|
||||
"Asia/Phnom_Penh": "SE Asia Standard Time",
|
||||
"Asia/Pontianak": "SE Asia Standard Time",
|
||||
"Asia/Pyongyang": "North Korea Standard Time",
|
||||
"Asia/Qatar": "Arab Standard Time",
|
||||
"Asia/Qostanay": "West Asia Standard Time",
|
||||
"Asia/Qyzylorda": "Qyzylorda Standard Time",
|
||||
"Asia/Rangoon": "Myanmar Standard Time",
|
||||
"Asia/Riyadh": "Arab Standard Time",
|
||||
"Asia/Saigon": "SE Asia Standard Time",
|
||||
"Asia/Sakhalin": "Sakhalin Standard Time",
|
||||
"Asia/Samarkand": "West Asia Standard Time",
|
||||
"Asia/Seoul": "Korea Standard Time",
|
||||
"Asia/Shanghai": "China Standard Time",
|
||||
"Asia/Singapore": "Singapore Standard Time",
|
||||
"Asia/Srednekolymsk": "Russia Time Zone 10",
|
||||
"Asia/Taipei": "Taipei Standard Time",
|
||||
"Asia/Tashkent": "West Asia Standard Time",
|
||||
"Asia/Tbilisi": "Georgian Standard Time",
|
||||
"Asia/Tehran": "Iran Standard Time",
|
||||
"Asia/Tel_Aviv": "Israel Standard Time",
|
||||
"Asia/Thimbu": "Bangladesh Standard Time",
|
||||
"Asia/Thimphu": "Bangladesh Standard Time",
|
||||
"Asia/Tokyo": "Tokyo Standard Time",
|
||||
"Asia/Tomsk": "Tomsk Standard Time",
|
||||
"Asia/Ujung_Pandang": "Singapore Standard Time",
|
||||
"Asia/Ulaanbaatar": "Ulaanbaatar Standard Time",
|
||||
"Asia/Ulan_Bator": "Ulaanbaatar Standard Time",
|
||||
"Asia/Urumqi": "Central Asia Standard Time",
|
||||
"Asia/Ust-Nera": "Vladivostok Standard Time",
|
||||
"Asia/Vientiane": "SE Asia Standard Time",
|
||||
"Asia/Vladivostok": "Vladivostok Standard Time",
|
||||
"Asia/Yakutsk": "Yakutsk Standard Time",
|
||||
"Asia/Yangon": "Myanmar Standard Time",
|
||||
"Asia/Yekaterinburg": "Ekaterinburg Standard Time",
|
||||
"Asia/Yerevan": "Caucasus Standard Time",
|
||||
"Atlantic/Azores": "Azores Standard Time",
|
||||
"Atlantic/Bermuda": "Atlantic Standard Time",
|
||||
"Atlantic/Canary": "GMT Standard Time",
|
||||
"Atlantic/Cape_Verde": "Cape Verde Standard Time",
|
||||
"Atlantic/Faeroe": "GMT Standard Time",
|
||||
"Atlantic/Faroe": "GMT Standard Time",
|
||||
"Atlantic/Jan_Mayen": "W. Europe Standard Time",
|
||||
"Atlantic/Madeira": "GMT Standard Time",
|
||||
"Atlantic/Reykjavik": "Greenwich Standard Time",
|
||||
"Atlantic/South_Georgia": "UTC-02",
|
||||
"Atlantic/St_Helena": "Greenwich Standard Time",
|
||||
"Atlantic/Stanley": "SA Eastern Standard Time",
|
||||
"Australia/ACT": "AUS Eastern Standard Time",
|
||||
"Australia/Adelaide": "Cen. Australia Standard Time",
|
||||
"Australia/Brisbane": "E. Australia Standard Time",
|
||||
"Australia/Broken_Hill": "Cen. Australia Standard Time",
|
||||
"Australia/Canberra": "AUS Eastern Standard Time",
|
||||
"Australia/Currie": "Tasmania Standard Time",
|
||||
"Australia/Darwin": "AUS Central Standard Time",
|
||||
"Australia/Eucla": "Aus Central W. Standard Time",
|
||||
"Australia/Hobart": "Tasmania Standard Time",
|
||||
"Australia/LHI": "Lord Howe Standard Time",
|
||||
"Australia/Lindeman": "E. Australia Standard Time",
|
||||
"Australia/Lord_Howe": "Lord Howe Standard Time",
|
||||
"Australia/Melbourne": "AUS Eastern Standard Time",
|
||||
"Australia/NSW": "AUS Eastern Standard Time",
|
||||
"Australia/North": "AUS Central Standard Time",
|
||||
"Australia/Perth": "W. Australia Standard Time",
|
||||
"Australia/Queensland": "E. Australia Standard Time",
|
||||
"Australia/South": "Cen. Australia Standard Time",
|
||||
"Australia/Sydney": "AUS Eastern Standard Time",
|
||||
"Australia/Tasmania": "Tasmania Standard Time",
|
||||
"Australia/Victoria": "AUS Eastern Standard Time",
|
||||
"Australia/West": "W. Australia Standard Time",
|
||||
"Australia/Yancowinna": "Cen. Australia Standard Time",
|
||||
"Brazil/Acre": "SA Pacific Standard Time",
|
||||
"Brazil/DeNoronha": "UTC-02",
|
||||
"Brazil/East": "E. South America Standard Time",
|
||||
"Brazil/West": "SA Western Standard Time",
|
||||
"Canada/Atlantic": "Atlantic Standard Time",
|
||||
"Canada/Central": "Manitoba Standard Time",
|
||||
"Canada/Eastern": "Eastern Standard Time",
|
||||
"Canada/Mountain": "Alberta Standard Time",
|
||||
"Canada/Newfoundland": "Newfoundland Standard Time",
|
||||
"Canada/Pacific": "British Columbia Standard Time",
|
||||
"Canada/Saskatchewan": "Canada Central Standard Time",
|
||||
"Canada/Yukon": "Yukon Standard Time",
|
||||
"Chile/Continental": "Pacific SA Standard Time",
|
||||
"Chile/EasterIsland": "Easter Island Standard Time",
|
||||
"Cuba": "Cuba Standard Time",
|
||||
"Egypt": "Egypt Standard Time",
|
||||
"Eire": "GMT Standard Time",
|
||||
"Etc/GMT": "UTC",
|
||||
"Etc/GMT+0": "UTC",
|
||||
"Etc/GMT+1": "Cape Verde Standard Time",
|
||||
"Etc/GMT+10": "Hawaiian Standard Time",
|
||||
"Etc/GMT+11": "UTC-11",
|
||||
"Etc/GMT+12": "Dateline Standard Time",
|
||||
"Etc/GMT+2": "UTC-02",
|
||||
"Etc/GMT+3": "SA Eastern Standard Time",
|
||||
"Etc/GMT+4": "SA Western Standard Time",
|
||||
"Etc/GMT+5": "SA Pacific Standard Time",
|
||||
"Etc/GMT+6": "Central America Standard Time",
|
||||
"Etc/GMT+7": "US Mountain Standard Time",
|
||||
"Etc/GMT+8": "UTC-08",
|
||||
"Etc/GMT+9": "UTC-09",
|
||||
"Etc/GMT-0": "UTC",
|
||||
"Etc/GMT-1": "W. Central Africa Standard Time",
|
||||
"Etc/GMT-10": "West Pacific Standard Time",
|
||||
"Etc/GMT-11": "Central Pacific Standard Time",
|
||||
"Etc/GMT-12": "UTC+12",
|
||||
"Etc/GMT-13": "UTC+13",
|
||||
"Etc/GMT-14": "Line Islands Standard Time",
|
||||
"Etc/GMT-2": "South Africa Standard Time",
|
||||
"Etc/GMT-3": "E. Africa Standard Time",
|
||||
"Etc/GMT-4": "Arabian Standard Time",
|
||||
"Etc/GMT-5": "West Asia Standard Time",
|
||||
"Etc/GMT-6": "Central Asia Standard Time",
|
||||
"Etc/GMT-7": "SE Asia Standard Time",
|
||||
"Etc/GMT-8": "Singapore Standard Time",
|
||||
"Etc/GMT-9": "Tokyo Standard Time",
|
||||
"Etc/GMT0": "UTC",
|
||||
"Etc/Greenwich": "UTC",
|
||||
"Etc/UCT": "UTC",
|
||||
"Etc/UTC": "UTC",
|
||||
"Etc/Universal": "UTC",
|
||||
"Etc/Zulu": "UTC",
|
||||
"Europe/Amsterdam": "W. Europe Standard Time",
|
||||
"Europe/Andorra": "W. Europe Standard Time",
|
||||
"Europe/Astrakhan": "Astrakhan Standard Time",
|
||||
"Europe/Athens": "GTB Standard Time",
|
||||
"Europe/Belfast": "GMT Standard Time",
|
||||
"Europe/Belgrade": "Central Europe Standard Time",
|
||||
"Europe/Berlin": "W. Europe Standard Time",
|
||||
"Europe/Bratislava": "Central Europe Standard Time",
|
||||
"Europe/Brussels": "Romance Standard Time",
|
||||
"Europe/Bucharest": "GTB Standard Time",
|
||||
"Europe/Budapest": "Central Europe Standard Time",
|
||||
"Europe/Busingen": "W. Europe Standard Time",
|
||||
"Europe/Chisinau": "E. Europe Standard Time",
|
||||
"Europe/Copenhagen": "Romance Standard Time",
|
||||
"Europe/Dublin": "GMT Standard Time",
|
||||
"Europe/Gibraltar": "W. Europe Standard Time",
|
||||
"Europe/Guernsey": "GMT Standard Time",
|
||||
"Europe/Helsinki": "FLE Standard Time",
|
||||
"Europe/Isle_of_Man": "GMT Standard Time",
|
||||
"Europe/Istanbul": "Turkey Standard Time",
|
||||
"Europe/Jersey": "GMT Standard Time",
|
||||
"Europe/Kaliningrad": "Kaliningrad Standard Time",
|
||||
"Europe/Kiev": "FLE Standard Time",
|
||||
"Europe/Kirov": "Russian Standard Time",
|
||||
"Europe/Kyiv": "FLE Standard Time",
|
||||
"Europe/Lisbon": "GMT Standard Time",
|
||||
"Europe/Ljubljana": "Central Europe Standard Time",
|
||||
"Europe/London": "GMT Standard Time",
|
||||
"Europe/Luxembourg": "W. Europe Standard Time",
|
||||
"Europe/Madrid": "Romance Standard Time",
|
||||
"Europe/Malta": "W. Europe Standard Time",
|
||||
"Europe/Mariehamn": "FLE Standard Time",
|
||||
"Europe/Minsk": "Belarus Standard Time",
|
||||
"Europe/Monaco": "W. Europe Standard Time",
|
||||
"Europe/Moscow": "Russian Standard Time",
|
||||
"Europe/Nicosia": "GTB Standard Time",
|
||||
"Europe/Oslo": "W. Europe Standard Time",
|
||||
"Europe/Paris": "Romance Standard Time",
|
||||
"Europe/Podgorica": "Central Europe Standard Time",
|
||||
"Europe/Prague": "Central Europe Standard Time",
|
||||
"Europe/Riga": "FLE Standard Time",
|
||||
"Europe/Rome": "W. Europe Standard Time",
|
||||
"Europe/Samara": "Russia Time Zone 3",
|
||||
"Europe/San_Marino": "W. Europe Standard Time",
|
||||
"Europe/Sarajevo": "Central European Standard Time",
|
||||
"Europe/Saratov": "Saratov Standard Time",
|
||||
"Europe/Simferopol": "Russian Standard Time",
|
||||
"Europe/Skopje": "Central European Standard Time",
|
||||
"Europe/Sofia": "FLE Standard Time",
|
||||
"Europe/Stockholm": "W. Europe Standard Time",
|
||||
"Europe/Tallinn": "FLE Standard Time",
|
||||
"Europe/Tirane": "Central Europe Standard Time",
|
||||
"Europe/Tiraspol": "E. Europe Standard Time",
|
||||
"Europe/Ulyanovsk": "Astrakhan Standard Time",
|
||||
"Europe/Vaduz": "W. Europe Standard Time",
|
||||
"Europe/Vatican": "W. Europe Standard Time",
|
||||
"Europe/Vienna": "W. Europe Standard Time",
|
||||
"Europe/Vilnius": "FLE Standard Time",
|
||||
"Europe/Volgograd": "Volgograd Standard Time",
|
||||
"Europe/Warsaw": "Central European Standard Time",
|
||||
"Europe/Zagreb": "Central European Standard Time",
|
||||
"Europe/Zurich": "W. Europe Standard Time",
|
||||
"GB": "GMT Standard Time",
|
||||
"GB-Eire": "GMT Standard Time",
|
||||
"GMT": "UTC",
|
||||
"GMT+0": "UTC",
|
||||
"GMT-0": "UTC",
|
||||
"GMT0": "UTC",
|
||||
"Greenwich": "UTC",
|
||||
"Hongkong": "China Standard Time",
|
||||
"Iceland": "Greenwich Standard Time",
|
||||
"Indian/Antananarivo": "E. Africa Standard Time",
|
||||
"Indian/Chagos": "Central Asia Standard Time",
|
||||
"Indian/Christmas": "SE Asia Standard Time",
|
||||
"Indian/Cocos": "Myanmar Standard Time",
|
||||
"Indian/Comoro": "E. Africa Standard Time",
|
||||
"Indian/Kerguelen": "West Asia Standard Time",
|
||||
"Indian/Mahe": "Mauritius Standard Time",
|
||||
"Indian/Maldives": "West Asia Standard Time",
|
||||
"Indian/Mauritius": "Mauritius Standard Time",
|
||||
"Indian/Mayotte": "E. Africa Standard Time",
|
||||
"Indian/Reunion": "Mauritius Standard Time",
|
||||
"Iran": "Iran Standard Time",
|
||||
"Israel": "Israel Standard Time",
|
||||
"Jamaica": "SA Pacific Standard Time",
|
||||
"Japan": "Tokyo Standard Time",
|
||||
"Kwajalein": "UTC+12",
|
||||
"Libya": "Libya Standard Time",
|
||||
"Mexico/BajaNorte": "Pacific Standard Time (Mexico)",
|
||||
"Mexico/BajaSur": "Mountain Standard Time (Mexico)",
|
||||
"Mexico/General": "Central Standard Time (Mexico)",
|
||||
"NZ": "New Zealand Standard Time",
|
||||
"NZ-CHAT": "Chatham Islands Standard Time",
|
||||
"Navajo": "Mountain Standard Time",
|
||||
"PRC": "China Standard Time",
|
||||
"Pacific/Apia": "Samoa Standard Time",
|
||||
"Pacific/Auckland": "New Zealand Standard Time",
|
||||
"Pacific/Bougainville": "Bougainville Standard Time",
|
||||
"Pacific/Chatham": "Chatham Islands Standard Time",
|
||||
"Pacific/Chuuk": "West Pacific Standard Time",
|
||||
"Pacific/Easter": "Easter Island Standard Time",
|
||||
"Pacific/Efate": "Central Pacific Standard Time",
|
||||
"Pacific/Enderbury": "UTC+13",
|
||||
"Pacific/Fakaofo": "UTC+13",
|
||||
"Pacific/Fiji": "Fiji Standard Time",
|
||||
"Pacific/Funafuti": "UTC+12",
|
||||
"Pacific/Galapagos": "Central America Standard Time",
|
||||
"Pacific/Gambier": "UTC-09",
|
||||
"Pacific/Guadalcanal": "Central Pacific Standard Time",
|
||||
"Pacific/Guam": "West Pacific Standard Time",
|
||||
"Pacific/Honolulu": "Hawaiian Standard Time",
|
||||
"Pacific/Johnston": "Hawaiian Standard Time",
|
||||
"Pacific/Kanton": "UTC+13",
|
||||
"Pacific/Kiritimati": "Line Islands Standard Time",
|
||||
"Pacific/Kosrae": "Central Pacific Standard Time",
|
||||
"Pacific/Kwajalein": "UTC+12",
|
||||
"Pacific/Majuro": "UTC+12",
|
||||
"Pacific/Marquesas": "Marquesas Standard Time",
|
||||
"Pacific/Midway": "UTC-11",
|
||||
"Pacific/Nauru": "UTC+12",
|
||||
"Pacific/Niue": "UTC-11",
|
||||
"Pacific/Norfolk": "Norfolk Standard Time",
|
||||
"Pacific/Noumea": "Central Pacific Standard Time",
|
||||
"Pacific/Pago_Pago": "UTC-11",
|
||||
"Pacific/Palau": "Tokyo Standard Time",
|
||||
"Pacific/Pitcairn": "UTC-08",
|
||||
"Pacific/Pohnpei": "Central Pacific Standard Time",
|
||||
"Pacific/Ponape": "Central Pacific Standard Time",
|
||||
"Pacific/Port_Moresby": "West Pacific Standard Time",
|
||||
"Pacific/Rarotonga": "Hawaiian Standard Time",
|
||||
"Pacific/Saipan": "West Pacific Standard Time",
|
||||
"Pacific/Samoa": "UTC-11",
|
||||
"Pacific/Tahiti": "Hawaiian Standard Time",
|
||||
"Pacific/Tarawa": "UTC+12",
|
||||
"Pacific/Tongatapu": "Tonga Standard Time",
|
||||
"Pacific/Truk": "West Pacific Standard Time",
|
||||
"Pacific/Wake": "UTC+12",
|
||||
"Pacific/Wallis": "UTC+12",
|
||||
"Poland": "Central European Standard Time",
|
||||
"Portugal": "GMT Standard Time",
|
||||
"ROC": "Taipei Standard Time",
|
||||
"ROK": "Korea Standard Time",
|
||||
"Singapore": "Singapore Standard Time",
|
||||
"Turkey": "Turkey Standard Time",
|
||||
"UCT": "UTC",
|
||||
"US/Alaska": "Alaskan Standard Time",
|
||||
"US/Aleutian": "Aleutian Standard Time",
|
||||
"US/Arizona": "US Mountain Standard Time",
|
||||
"US/Central": "Central Standard Time",
|
||||
"US/Eastern": "Eastern Standard Time",
|
||||
"US/Hawaii": "Hawaiian Standard Time",
|
||||
"US/Indiana-Starke": "Central Standard Time",
|
||||
"US/Michigan": "Eastern Standard Time",
|
||||
"US/Mountain": "Mountain Standard Time",
|
||||
"US/Pacific": "Pacific Standard Time",
|
||||
"US/Samoa": "UTC-11",
|
||||
"UTC": "UTC",
|
||||
"Universal": "UTC",
|
||||
"W-SU": "Russian Standard Time",
|
||||
"Zulu": "UTC",
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
|
||||
|
||||
:class:`WindowsScheduledJobsMixin` implements napalm-device-types'
|
||||
:class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin` for the driver,
|
||||
which carries each script across ``PsrpTransport.run``.
|
||||
|
||||
**Reading** is one script: every task (``Get-ScheduledTask``) with what the host
|
||||
says of its runs (``Get-ScheduledTaskInfo``), projected onto flat fields, and the
|
||||
host's time zone; Python only normalises. Every task is a job ``task:<path><name>``
|
||||
whose schedule is a summary of its triggers. A task under ``\\Microsoft\\`` is the
|
||||
``platform``'s, any other the ``admin``'s -- Windows does not say which software
|
||||
installed a task -- and a task in the root folder whose description starts with
|
||||
``napalm-scheduled-job: <its name>`` is an ``application``'s, read back as the cron
|
||||
expression and command it was written with (:mod:`napalm_windows.task_xml`). Its
|
||||
digest covers its triggers as well, so triggers changed by hand are a change. A
|
||||
reading whose task count does not match, or whose JSON is cut short, raises.
|
||||
|
||||
**Switching** is the task's own flag (``Enable-`` / ``Disable-ScheduledTask``);
|
||||
**running** is ``Start-ScheduledTask``, which returns once the task has started: how
|
||||
the run ends shows in the next reading. A disabled task, or one that does not allow a
|
||||
start on demand, is not offered ``run``. A task is addressed by its exact path and
|
||||
name, never by ``-TaskName``, which takes wildcards.
|
||||
|
||||
**An application's own job** is registered from XML (``Register-ScheduledTask -Xml
|
||||
-Force``), so creating it and changing it write the whole definition the same way;
|
||||
``delete_scheduled_job`` unregisters it. Before every write the job is read again
|
||||
and compared with the digest the caller saw; a task of the same name that an
|
||||
application did not write is never overwritten. Every value goes into PowerShell
|
||||
single-quoted, its quotes doubled.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
from napalm_device_types import (
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobDict,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobResultDict,
|
||||
ScheduledJobsMixin,
|
||||
ScheduledJobSpecDict,
|
||||
ScheduledJobsReadingDict,
|
||||
job_digest,
|
||||
)
|
||||
from napalm_device_types.scheduled_jobs import ACTIONS, DELETE, EDIT, check_spec
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.task_xml import JOB_MARKER, SCHEDULE_LINE, own_command, task_xml
|
||||
from napalm_windows.time_zones import iana_time_zone
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
# Every task with its run info. Times leave the host as ISO 8601 in UTC; a task
|
||||
# whose run info cannot be read keeps its definition and loses only its times.
|
||||
_PS_SCHEDULED_TASKS = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function U($d) { if ($d) { ([datetime]$d).ToUniversalTime().ToString('o') } }
|
||||
$tasks = @(Get-ScheduledTask)
|
||||
$rows = @($tasks | ForEach-Object {
|
||||
$t = $_
|
||||
$i = $t | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
|
||||
[pscustomobject]@{
|
||||
path = $t.TaskPath
|
||||
name = $t.TaskName
|
||||
state = [string]$t.State
|
||||
user = $t.Principal.UserId
|
||||
group = $t.Principal.GroupId
|
||||
on_demand = $t.Settings.AllowDemandStart
|
||||
description = $t.Description
|
||||
actions = @($t.Actions | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
class = $_.CimClass.CimClassName
|
||||
execute = $_.Execute
|
||||
arguments = $_.Arguments
|
||||
class_id = $_.ClassId
|
||||
}
|
||||
})
|
||||
triggers = @($t.Triggers | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
class = $_.CimClass.CimClassName
|
||||
enabled = $_.Enabled
|
||||
start = [string]$_.StartBoundary
|
||||
days_interval = $_.DaysInterval
|
||||
weeks_interval = $_.WeeksInterval
|
||||
days_of_week = $_.DaysOfWeek
|
||||
interval = [string]$_.Repetition.Interval
|
||||
duration = [string]$_.Repetition.Duration
|
||||
delay = [string]$_.Delay
|
||||
}
|
||||
})
|
||||
last_run = U $i.LastRunTime
|
||||
last_result = $i.LastTaskResult
|
||||
next_run = U $i.NextRunTime
|
||||
}
|
||||
})
|
||||
ConvertTo-Json -Compress -Depth 5 -InputObject ([pscustomobject]@{
|
||||
time_zone = [System.TimeZoneInfo]::Local.Id
|
||||
count = $tasks.Count
|
||||
tasks = $rows
|
||||
})
|
||||
"""
|
||||
|
||||
# One task by its exact path and name, handed to a cmdlet.
|
||||
_PS_TASK_CMDLET = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$task = @(Get-ScheduledTask | Where-Object {{ $_.TaskPath -eq {path} -and $_.TaskName -eq {name} }})
|
||||
if ($task.Count -ne 1) {{ throw ('no single scheduled task ' + {path} + {name}) }}
|
||||
$task[0] | {cmdlet} | Out-Null
|
||||
"""
|
||||
|
||||
_PS_REGISTER = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Register-ScheduledTask -TaskPath {path} -TaskName {name} -Xml {xml} -Force | Out-Null
|
||||
"""
|
||||
|
||||
_PS_UNREGISTER = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Unregister-ScheduledTask -TaskPath {path} -TaskName {name} -Confirm:$false
|
||||
"""
|
||||
|
||||
_CMDLETS = {
|
||||
"enable": ("Enable-ScheduledTask", "enabled"),
|
||||
"disable": ("Disable-ScheduledTask", "disabled"),
|
||||
"run": (
|
||||
"Start-ScheduledTask",
|
||||
"started; Start-ScheduledTask returns once it has started, so how the run "
|
||||
"ends shows in the next reading",
|
||||
),
|
||||
}
|
||||
|
||||
_ROOT = "\\"
|
||||
_JOB_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
|
||||
_DOTNET_DATE = re.compile(r"^/Date\((-?\d+)(?:[+-]\d{4})?\)/$")
|
||||
_BOUNDARY = re.compile(r"^(\d{4}-\d\d-\d\d)T(\d\d:\d\d)(?::\d\d(?:\.\d+)?)?(Z|[+-]\d\d:\d\d)?$")
|
||||
_DURATION = re.compile(r"^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$")
|
||||
_DURATION_UNITS = ("day", "hour", "minute", "second")
|
||||
|
||||
#: LastTaskResult: SCHED_S_TASK_RUNNING and SCHED_S_TASK_HAS_NOT_RUN.
|
||||
_RUNNING = 0x41301
|
||||
_NEVER_RAN = 0x41303
|
||||
|
||||
_WEEKDAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
|
||||
_EVENT_TRIGGERS = {
|
||||
"MSFT_TaskBootTrigger": "at startup",
|
||||
"MSFT_TaskLogonTrigger": "at logon",
|
||||
"MSFT_TaskIdleTrigger": "on idle",
|
||||
"MSFT_TaskEventTrigger": "on an event",
|
||||
"MSFT_TaskSessionStateChangeTrigger": "session state change",
|
||||
"MSFT_TaskRegistrationTrigger": "at registration",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _timestamp(value: Any) -> str | None:
|
||||
"""A time as the host gave it -- ISO 8601, ``/Date(ms)/`` or epoch seconds -- as
|
||||
ISO 8601 in UTC; None for none, and for Task Scheduler's never (30 November 1999)."""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, int | float):
|
||||
at = datetime.fromtimestamp(value, UTC)
|
||||
elif match := _DOTNET_DATE.match(str(value).strip()):
|
||||
at = datetime.fromtimestamp(int(match[1]) / 1000, UTC)
|
||||
else:
|
||||
try:
|
||||
at = datetime.fromisoformat(str(value).strip())
|
||||
except ValueError:
|
||||
return None
|
||||
at = (at if at.tzinfo else at.replace(tzinfo=UTC)).astimezone(UTC)
|
||||
return None if at.year < 2000 else at.isoformat()
|
||||
|
||||
|
||||
def _last_result(code: Any, last_run: str | None) -> str | None:
|
||||
if last_run is None or code is None:
|
||||
return None
|
||||
code = int(code) & 0xFFFFFFFF
|
||||
if code == _NEVER_RAN:
|
||||
return None
|
||||
if code == _RUNNING:
|
||||
return "running"
|
||||
return "success" if code == 0 else f"0x{code:X}"
|
||||
|
||||
|
||||
def _readable_duration(value: str) -> str:
|
||||
"""``PT1H30M`` → ``1 hour 30 minutes``; anything else as it is."""
|
||||
match = _DURATION.match(value)
|
||||
if not match or not any(match.groups()):
|
||||
return value
|
||||
parts = [
|
||||
f"{n} {unit}{'' if n == '1' else 's'}"
|
||||
for n, unit in zip(match.groups(), _DURATION_UNITS, strict=True)
|
||||
if n
|
||||
]
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _clock(start: str) -> tuple[str, str]:
|
||||
"""A trigger's start boundary as its date and its time of day (with its offset)."""
|
||||
match = _BOUNDARY.match(start)
|
||||
if not match:
|
||||
return "", start
|
||||
return match[1], match[2] + (match[3] or "")
|
||||
|
||||
|
||||
def _every(count: Any, unit: str) -> str:
|
||||
return f"{unit}ly" if count in (None, 0, 1) else f"every {count} {unit}s"
|
||||
|
||||
|
||||
def _calendar(trigger: dict[str, Any], cls: str) -> str:
|
||||
date, time = _clock(str(trigger.get("start") or ""))
|
||||
at = f" at {time}" if time else ""
|
||||
if cls == "MSFT_TaskDailyTrigger":
|
||||
days = trigger.get("days_interval")
|
||||
return ("daily" if days in (None, 0, 1) else f"every {days} days") + at
|
||||
if cls == "MSFT_TaskWeeklyTrigger":
|
||||
mask = int(trigger.get("days_of_week") or 0)
|
||||
days = ",".join(d for i, d in enumerate(_WEEKDAYS) if mask & (1 << i))
|
||||
return f"{_every(trigger.get('weeks_interval'), 'week')} on {days}{at}"
|
||||
if cls == "MSFT_TaskTimeTrigger":
|
||||
return f"once at {date} {time}".rstrip()
|
||||
return f"trigger{at}"
|
||||
|
||||
|
||||
def _trigger(trigger: dict[str, Any]) -> str:
|
||||
"""One trigger as a short sentence: its kind, when, how it repeats."""
|
||||
cls = str(trigger.get("class") or "")
|
||||
text = _EVENT_TRIGGERS.get(cls) or _calendar(trigger, cls)
|
||||
if trigger.get("delay"):
|
||||
text += f" after {_readable_duration(str(trigger['delay']))}"
|
||||
if trigger.get("interval"):
|
||||
text += f", every {_readable_duration(str(trigger['interval']))}"
|
||||
if trigger.get("duration"):
|
||||
text += f" for {_readable_duration(str(trigger['duration']))}"
|
||||
if trigger.get("enabled") is False:
|
||||
text += " (disabled)"
|
||||
return text
|
||||
|
||||
|
||||
def _action(action: dict[str, Any]) -> str:
|
||||
if action.get("execute"):
|
||||
return " ".join(str(p) for p in (action["execute"], action.get("arguments")) if p)
|
||||
if action.get("class_id"):
|
||||
return f"COM handler {action['class_id']}"
|
||||
return str(action.get("class") or "")
|
||||
|
||||
|
||||
class _Own(NamedTuple):
|
||||
"""What an application's task description and action say of the job."""
|
||||
|
||||
name: str
|
||||
description: str
|
||||
schedule: str | None
|
||||
command: str | None
|
||||
|
||||
|
||||
def _own(path: str, name: str, task: dict[str, Any]) -> _Own | None:
|
||||
"""The application's job this task is; None for any other task."""
|
||||
lines = str(task.get("description") or "").splitlines()
|
||||
if path != _ROOT or not lines or not lines[0].startswith(JOB_MARKER):
|
||||
return None
|
||||
job_name, _, description = lines[0][len(JOB_MARKER) :].partition(" ")
|
||||
if job_name != name or not _JOB_NAME.fullmatch(name):
|
||||
return None
|
||||
schedule = next(
|
||||
(ln[len(SCHEDULE_LINE) :] for ln in lines[1:] if ln.startswith(SCHEDULE_LINE)), None
|
||||
)
|
||||
actions = _as_list(task.get("actions"))
|
||||
command = (
|
||||
own_command(actions[0].get("execute"), actions[0].get("arguments"))
|
||||
if len(actions) == 1
|
||||
else None
|
||||
)
|
||||
return _Own(name, description.strip(), schedule, command)
|
||||
|
||||
|
||||
def _verbs(task: dict[str, Any], enabled: bool, own: bool) -> list[str]:
|
||||
verbs = ["enable", "disable"]
|
||||
if enabled and task.get("on_demand") is not False:
|
||||
verbs.append("run")
|
||||
return [*verbs, EDIT, DELETE] if own else verbs
|
||||
|
||||
|
||||
class _Definition(NamedTuple):
|
||||
"""What a task's fields say it does, as the job shows it."""
|
||||
|
||||
schedule: str
|
||||
schedule_kind: str
|
||||
command: str
|
||||
managed_by: str
|
||||
description: str
|
||||
|
||||
|
||||
def _definition(path: str, task: dict[str, Any], triggers: str, own: _Own | None) -> _Definition:
|
||||
command = "\n".join(_action(a) for a in _as_list(task.get("actions")))
|
||||
if own is not None:
|
||||
kind = "cron" if own.schedule else "triggers"
|
||||
return _Definition(
|
||||
own.schedule or triggers, kind, own.command or command, "application", own.description
|
||||
)
|
||||
platform = path.lower().startswith("\\microsoft\\")
|
||||
return _Definition(
|
||||
triggers,
|
||||
"triggers",
|
||||
command,
|
||||
"platform" if platform else "admin",
|
||||
str(task.get("description") or "").strip(),
|
||||
)
|
||||
|
||||
|
||||
def _task_job(task: dict[str, Any]) -> ScheduledJobDict:
|
||||
path, name = str(task.get("path") or _ROOT), str(task.get("name") or "")
|
||||
triggers = "; ".join(_trigger(t) for t in _as_list(task.get("triggers")))
|
||||
enabled = str(task.get("state") or "").lower() != "disabled"
|
||||
own = _own(path, name, task)
|
||||
found = _definition(path, task, triggers, own)
|
||||
last_run = _timestamp(task.get("last_run"))
|
||||
job: ScheduledJobDict = {
|
||||
"key": f"task:{path}{name}",
|
||||
"kind": "task",
|
||||
"source": f"{path}{name}",
|
||||
"run_as": str(task.get("user") or task.get("group") or ""),
|
||||
"schedule": found.schedule,
|
||||
"schedule_kind": found.schedule_kind,
|
||||
"command": found.command,
|
||||
"enabled": enabled,
|
||||
"managed_by": found.managed_by,
|
||||
"digest": "",
|
||||
"actions": _verbs(task, enabled, own is not None),
|
||||
"last_run": last_run,
|
||||
"last_result": _last_result(task.get("last_result"), last_run),
|
||||
"next_run": _timestamp(task.get("next_run")),
|
||||
}
|
||||
# An application's task shows its cron line; its triggers are what runs.
|
||||
job["digest"] = job_digest(dict(job), content=triggers if own else "")
|
||||
if own is not None:
|
||||
job["name"] = own.name
|
||||
if found.description:
|
||||
job["description"] = found.description
|
||||
return job
|
||||
|
||||
|
||||
def parse_reading(output: str) -> tuple[list[ScheduledJobDict], str | None]:
|
||||
"""The jobs and the IANA time zone in what :data:`_PS_SCHEDULED_TASKS` printed.
|
||||
|
||||
:raises ValueError: when the reading is cut short or holds fewer tasks than counted.
|
||||
"""
|
||||
raw = json.loads(output)
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("not a scheduled-tasks reading")
|
||||
tasks = _as_list(raw.get("tasks"))
|
||||
count = int(raw.get("count") or 0)
|
||||
if len(tasks) != count:
|
||||
raise ValueError(f"the reading holds {len(tasks)} of {count} scheduled tasks")
|
||||
return [_task_job(t) for t in tasks], iana_time_zone(raw.get("time_zone"))
|
||||
|
||||
|
||||
def _path_and_name(source: str) -> tuple[str, str]:
|
||||
path, _, name = source.rpartition("\\")
|
||||
return path + "\\", name
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The mixin
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsScheduledJobsMixin(ScheduledJobsMixin):
|
||||
"""The Task Scheduler as scheduled jobs; the driver carries the scripts."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def _sj_read(self) -> tuple[list[ScheduledJobDict], str | None]:
|
||||
return parse_reading(self._run_raw(_PS_SCHEDULED_TASKS))
|
||||
|
||||
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
|
||||
"""Every task of the host, in one round trip.
|
||||
|
||||
:raises ValueError: when the reading came back cut short.
|
||||
"""
|
||||
jobs, time_zone = self._sj_read()
|
||||
return {"jobs": jobs, "time_zone": time_zone}
|
||||
|
||||
def _sj_job(self, key: str, digest: str) -> ScheduledJobDict:
|
||||
jobs, _ = self._sj_read()
|
||||
job = next((j for j in jobs if j["key"] == key), None)
|
||||
if job is None:
|
||||
raise LookupError(f"no scheduled job {key}")
|
||||
if job["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
|
||||
return job
|
||||
|
||||
def _sj_send(self, script: str, done: str) -> ScheduledJobResultDict:
|
||||
try:
|
||||
self._run_raw(script)
|
||||
except PowerShellError as exc:
|
||||
return {"success": False, "output": str(exc)}
|
||||
return {"success": True, "output": done}
|
||||
|
||||
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Enable, disable or start the task *key*; see :class:`ScheduledJobsMixin`."""
|
||||
if action not in ACTIONS:
|
||||
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
|
||||
job = self._sj_job(key, digest)
|
||||
if action not in job["actions"]:
|
||||
raise ScheduledJobRefused(
|
||||
f"{key} cannot be told to {action}: it is disabled or "
|
||||
"does not allow a start on demand"
|
||||
)
|
||||
cmdlet, done = _CMDLETS[action]
|
||||
path, name = _path_and_name(job["source"])
|
||||
script = _PS_TASK_CMDLET.format(path=_ps_quote(path), name=_ps_quote(name), cmdlet=cmdlet)
|
||||
return self._sj_send(script, f"{key} {done}")
|
||||
|
||||
def _sj_own(self, spec: ScheduledJobSpecDict, digest: str | None) -> ScheduledJobDict | None:
|
||||
key = f"task:{_ROOT}{spec['name']}"
|
||||
jobs, _ = self._sj_read()
|
||||
# Task names are case-insensitive: Register -Force would replace "\Name" too.
|
||||
current = next((j for j in jobs if j["key"].lower() == key), None)
|
||||
if digest is None:
|
||||
if current is not None:
|
||||
raise ScheduledJobChanged(f"a task {current['source']} is there already")
|
||||
return None
|
||||
if current is None:
|
||||
raise LookupError(f"no scheduled job {key}")
|
||||
if current["managed_by"] != "application":
|
||||
raise ScheduledJobRefused(f"{current['key']} was not written by an application")
|
||||
if current["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
|
||||
return current
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Register or change the application's own task; see :class:`ScheduledJobsMixin`."""
|
||||
check_spec(spec)
|
||||
xml = task_xml(spec)
|
||||
current = self._sj_own(spec, digest)
|
||||
script = _PS_REGISTER.format(
|
||||
path=_ps_quote(_ROOT), name=_ps_quote(spec["name"]), xml=_ps_quote(xml)
|
||||
)
|
||||
verb = "changed" if current else "created"
|
||||
return self._sj_send(script, f"task:{_ROOT}{spec['name']} {verb}")
|
||||
|
||||
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Unregister the application's task *key*; see :class:`ScheduledJobsMixin`."""
|
||||
job = self._sj_job(key, digest)
|
||||
if job["managed_by"] != "application":
|
||||
raise ScheduledJobRefused(
|
||||
f"{key} was not written by an application; it is only switched"
|
||||
)
|
||||
path, name = _path_and_name(job["source"])
|
||||
script = _PS_UNREGISTER.format(path=_ps_quote(path), name=_ps_quote(name))
|
||||
return self._sj_send(script, f"{key} deleted")
|
||||
@@ -0,0 +1,355 @@
|
||||
"""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
|
||||
@@ -0,0 +1,249 @@
|
||||
"""An application's scheduled job as Task Scheduler XML (#8). Pure: no I/O.
|
||||
|
||||
:meth:`~napalm_windows.scheduled_tasks.WindowsScheduledJobsMixin.put_scheduled_job`
|
||||
registers the task this module writes, in the root folder ``\\``, named by the job.
|
||||
|
||||
**The cron expression becomes triggers, exactly or not at all.** A day schedule is
|
||||
one of Task Scheduler's: every day (``ScheduleByDay``), weekdays
|
||||
(``ScheduleByWeek``), or days of the month in some months (``ScheduleByMonth``).
|
||||
The times of day become one trigger at the first time with a repetition when they
|
||||
are three or more evenly spaced (``*/5``, ``*/15 8-17``, ``0 */6``), else one trigger per time,
|
||||
else one repeating trigger per hour when the minutes are evenly spaced (``*/7``) --
|
||||
at most 48 triggers, Task Scheduler's limit. ``@reboot`` is a boot trigger. What
|
||||
Task Scheduler cannot say is refused, naming why: cron's *either* rule (both day
|
||||
fields set), a weekday together with days of the month or with months, and times
|
||||
that need more than 48 triggers. A trigger's start is a local time without an
|
||||
offset, so it follows the host's clock as cron does; a repetition counts elapsed
|
||||
time, so on the day summer time starts or ends its later runs shift by the hour.
|
||||
|
||||
**The command runs in ``cmd.exe``**: ``cmd.exe /d /s /c "<command>"`` -- ``/d``
|
||||
skips AutoRun, ``/s`` keeps the command as it is between the outer quotes. One line,
|
||||
as a command line is; the reading gives it back as it was written.
|
||||
|
||||
**The principal** is ``SYSTEM`` (the local system account) or a local user, who
|
||||
runs it whether logged on or not without a stored password (``S4U``): such a run
|
||||
has no network credentials, so a share needs the computer's access.
|
||||
|
||||
**The description** is ``napalm-scheduled-job: <name> <description>`` and a second
|
||||
line ``schedule: <cron expression>``: the job's name, and its schedule as the
|
||||
application gave it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from itertools import pairwise
|
||||
|
||||
from napalm_device_types import ScheduledJobRefused, ScheduledJobSpecDict
|
||||
from napalm_device_types.cron import CronSchedule, is_reboot, parse_cron
|
||||
|
||||
#: The first line of an application's task description, before its name.
|
||||
JOB_MARKER = "napalm-scheduled-job: "
|
||||
#: The line of an application's task description that holds its cron expression.
|
||||
SCHEDULE_LINE = "schedule: "
|
||||
|
||||
CMD = "%SystemRoot%\\System32\\cmd.exe"
|
||||
_CMD_PREFIX = '/d /s /c "'
|
||||
|
||||
#: Task Scheduler's limit of triggers on one task.
|
||||
MAX_TRIGGERS = 48
|
||||
_START_DATE = "2020-01-01"
|
||||
_SYSTEM_SID = "S-1-5-18"
|
||||
_NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task"
|
||||
|
||||
_WEEKDAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
|
||||
_MONTHS = (
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
)
|
||||
_ALL_DAYS = frozenset(range(1, 32))
|
||||
_ALL_MONTHS = frozenset(range(1, 13))
|
||||
_ALL_WEEKDAYS = frozenset(range(7))
|
||||
|
||||
#: (minute of the day it starts, repetition interval, repetition duration) in minutes.
|
||||
_Clock = tuple[int, int | None, int | None]
|
||||
|
||||
|
||||
# -- the command ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
"""*text* as XML character data."""
|
||||
return html.escape(text, quote=False)
|
||||
|
||||
|
||||
def _check_text(what: str, text: str) -> None:
|
||||
if "\n" in text or "\r" in text:
|
||||
raise ScheduledJobRefused(f"a task's {what} is one line")
|
||||
if any(ord(c) < 32 and c != "\t" for c in text):
|
||||
raise ScheduledJobRefused(f"a task's {what} cannot hold a control character")
|
||||
|
||||
|
||||
def command_action(command: str) -> tuple[str, str]:
|
||||
"""The ``Exec`` action's command and arguments that run *command* in ``cmd.exe``."""
|
||||
command = command.strip()
|
||||
_check_text("command", command)
|
||||
return CMD, f'{_CMD_PREFIX}{command}"'
|
||||
|
||||
|
||||
def own_command(execute: str | None, arguments: str | None) -> str | None:
|
||||
"""The command :func:`command_action` wrapped; None for any other action."""
|
||||
args = arguments or ""
|
||||
if (execute or "").lower() != CMD.lower():
|
||||
return None
|
||||
if not (args.startswith(_CMD_PREFIX) and args.endswith('"') and len(args) > len(_CMD_PREFIX)):
|
||||
return None
|
||||
return args[len(_CMD_PREFIX) : -1]
|
||||
|
||||
|
||||
def description(spec: ScheduledJobSpecDict) -> str:
|
||||
"""The task's description: the job's name and description, then its cron expression."""
|
||||
first = f"{JOB_MARKER}{spec['name']} {spec.get('description') or ''}".rstrip()
|
||||
return f"{first}\n{SCHEDULE_LINE}{spec['schedule'].strip()}"
|
||||
|
||||
|
||||
# -- the schedule --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _evenly_spaced(values: list[int]) -> int | None:
|
||||
"""The step between *values*, two or more; None when they are not evenly spaced."""
|
||||
if len(values) < 2:
|
||||
return None
|
||||
step = values[1] - values[0]
|
||||
return step if all(b - a == step for a, b in pairwise(values)) else None
|
||||
|
||||
|
||||
def _clocks(s: CronSchedule) -> list[_Clock]:
|
||||
times = sorted(h * 60 + m for h in s.hours for m in s.minutes)
|
||||
step = _evenly_spaced(times)
|
||||
if step is not None and len(times) > 2:
|
||||
return [(times[0], step, times[-1] - times[0] + 1)]
|
||||
if len(times) <= MAX_TRIGGERS:
|
||||
return [(t, None, None) for t in times]
|
||||
minutes = sorted(s.minutes)
|
||||
step = _evenly_spaced(minutes)
|
||||
if step is not None and len(s.hours) <= MAX_TRIGGERS:
|
||||
span = minutes[-1] - minutes[0] + 1
|
||||
return [(h * 60 + minutes[0], step, span) for h in sorted(s.hours)]
|
||||
raise ScheduledJobRefused(
|
||||
f"these times of day need more than {MAX_TRIGGERS} triggers, Task Scheduler's limit"
|
||||
)
|
||||
|
||||
|
||||
def _names(names: tuple[str, ...], values: frozenset[int], first: int) -> str:
|
||||
return "".join(f"<{names[v - first]} />" for v in sorted(values))
|
||||
|
||||
|
||||
def _day_schedule(s: CronSchedule) -> str:
|
||||
if s.either_day:
|
||||
raise ScheduledJobRefused(
|
||||
"Task Scheduler cannot fire on either a day of the month or a weekday, "
|
||||
"as cron does when both are set"
|
||||
)
|
||||
every_date = s.days == _ALL_DAYS and s.months == _ALL_MONTHS
|
||||
if s.weekdays == _ALL_WEEKDAYS and every_date:
|
||||
return "<ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>"
|
||||
if every_date:
|
||||
days = _names(_WEEKDAYS, s.weekdays, 0)
|
||||
return (
|
||||
f"<ScheduleByWeek><DaysOfWeek>{days}</DaysOfWeek>"
|
||||
"<WeeksInterval>1</WeeksInterval></ScheduleByWeek>"
|
||||
)
|
||||
if s.weekdays == _ALL_WEEKDAYS:
|
||||
days = "".join(f"<Day>{d}</Day>" for d in sorted(s.days))
|
||||
months = _names(_MONTHS, s.months, 1)
|
||||
return (
|
||||
f"<ScheduleByMonth><DaysOfMonth>{days}</DaysOfMonth>"
|
||||
f"<Months>{months}</Months></ScheduleByMonth>"
|
||||
)
|
||||
raise ScheduledJobRefused(
|
||||
"Task Scheduler cannot combine a weekday with days of the month or with months"
|
||||
)
|
||||
|
||||
|
||||
def _duration(minutes: int) -> str:
|
||||
hours, rest = divmod(minutes, 60)
|
||||
return "PT" + (f"{hours}H" if hours else "") + (f"{rest}M" if rest or not hours else "")
|
||||
|
||||
|
||||
def _calendar_trigger(clock: _Clock, day_schedule: str) -> str:
|
||||
start, interval, duration = clock
|
||||
repetition = ""
|
||||
if interval is not None and duration is not None:
|
||||
repetition = (
|
||||
f"<Repetition><Interval>{_duration(interval)}</Interval>"
|
||||
f"<Duration>{_duration(duration)}</Duration>"
|
||||
"<StopAtDurationEnd>false</StopAtDurationEnd></Repetition>"
|
||||
)
|
||||
hour, minute = divmod(start, 60)
|
||||
return (
|
||||
f"<CalendarTrigger>{repetition}"
|
||||
f"<StartBoundary>{_START_DATE}T{hour:02d}:{minute:02d}:00</StartBoundary>"
|
||||
f"<Enabled>true</Enabled>{day_schedule}</CalendarTrigger>"
|
||||
)
|
||||
|
||||
|
||||
def triggers(schedule: str) -> list[str]:
|
||||
"""The triggers that fire exactly when the cron expression *schedule* does.
|
||||
|
||||
:raises ScheduledJobRefused: for a shape Task Scheduler cannot express, or an
|
||||
expression cron would not take.
|
||||
"""
|
||||
if is_reboot(schedule):
|
||||
return ["<BootTrigger><Enabled>true</Enabled></BootTrigger>"]
|
||||
try:
|
||||
s = parse_cron(schedule)
|
||||
except ValueError as exc:
|
||||
raise ScheduledJobRefused(str(exc)) from exc
|
||||
day_schedule = _day_schedule(s)
|
||||
return [_calendar_trigger(clock, day_schedule) for clock in _clocks(s)]
|
||||
|
||||
|
||||
# -- the task ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _principal(run_as: str) -> str:
|
||||
if run_as.upper() == "SYSTEM":
|
||||
return f"<UserId>{_SYSTEM_SID}</UserId><RunLevel>HighestAvailable</RunLevel>"
|
||||
return (
|
||||
f"<UserId>{_escape(run_as)}</UserId><LogonType>S4U</LogonType>"
|
||||
"<RunLevel>LeastPrivilege</RunLevel>"
|
||||
)
|
||||
|
||||
|
||||
def task_xml(spec: ScheduledJobSpecDict) -> str:
|
||||
"""The whole task for *spec*, as ``Register-ScheduledTask -Xml`` takes it.
|
||||
|
||||
:raises ScheduledJobRefused: for a schedule, command or description a task
|
||||
cannot hold.
|
||||
"""
|
||||
execute, arguments = command_action(spec["command"])
|
||||
_check_text("description", spec.get("description") or "")
|
||||
trigger_xml = "".join(triggers(spec["schedule"]))
|
||||
enabled = "true" if spec["enabled"] else "false"
|
||||
return (
|
||||
f'<Task version="1.2" xmlns="{_NAMESPACE}">'
|
||||
f"<RegistrationInfo><Description>{_escape(description(spec))}</Description>"
|
||||
"</RegistrationInfo>"
|
||||
f"<Triggers>{trigger_xml}</Triggers>"
|
||||
f'<Principals><Principal id="Author">{_principal(spec["run_as"])}</Principal></Principals>'
|
||||
"<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>"
|
||||
"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"
|
||||
"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"
|
||||
"<StartWhenAvailable>false</StartWhenAvailable>"
|
||||
"<AllowStartOnDemand>true</AllowStartOnDemand>"
|
||||
f"<Enabled>{enabled}</Enabled></Settings>"
|
||||
f'<Actions Context="Author"><Exec><Command>{_escape(execute)}</Command>'
|
||||
f"<Arguments>{_escape(arguments)}</Arguments></Exec></Actions>"
|
||||
"</Task>"
|
||||
)
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Time sync on Windows: the Windows Time service (w32time) and the time zone (NetOrk/netork#2367).
|
||||
|
||||
:class:`WindowsTimeSyncMixin` implements napalm-device-types'
|
||||
:class:`~napalm_device_types.time_sync.TimeSyncMixin` for the driver, which carries
|
||||
each script across ``PsrpTransport.run``.
|
||||
|
||||
**Reading** is one script. The servers and the mode are w32time's registry values
|
||||
(``Type``, ``NtpServer``), where group policy's override the local ones -- the
|
||||
registry, not ``w32tm /query /configuration``, whose text is in the host's language.
|
||||
``NtpServer`` lists ``name,0xFLAGS`` pairs; the flags are dropped. ``Type NoSync``
|
||||
takes time from nowhere: no servers. Synchronised is the leap indicator of
|
||||
``w32tm /query /status`` (``3`` = not synchronised), the one value on the first line
|
||||
whatever the language; a stopped service is not synchronised. The zone is what
|
||||
``tzutil /g`` reads, the registry's ``TimeZoneInformation`` (``TimeZoneKeyName``), as an
|
||||
IANA name (:mod:`napalm_windows.time_zones`); one with summer time switched off
|
||||
(``DynamicDaylightTimeDisabled``, tzutil's ``_dstoff``) is not that zone, and reads as
|
||||
None. The registry is read anew each time, where ``[TimeZoneInfo]::Local`` is cached
|
||||
for the life of the remote session.
|
||||
|
||||
**Writing the servers** is what ``w32tm /config /manualpeerlist:"a,0x8 b,0x8"
|
||||
/syncfromflags:manual`` writes -- ``NtpServer`` (``0x8``: client mode, which public
|
||||
servers answer) and ``Type NTP`` -- set with ``Set-ItemProperty``, then
|
||||
``w32tm /config /update``, after starting the service where it is stopped. No value
|
||||
goes through a native command line, whose quoting Windows PowerShell 5.1 mangles.
|
||||
Two kinds of host are refused before anything is written: a domain member that takes
|
||||
its time from the domain hierarchy (``NT5DS``, ``AllSync``) -- the domain sets its
|
||||
time, not the host -- and a host whose w32time settings come from group policy, which
|
||||
would override the write.
|
||||
|
||||
**Writing the zone** is ``Set-TimeZone -Id`` (``tzutil /s``), which also switches summer
|
||||
time back on. Windows keeps a Windows zone, which stands for
|
||||
several IANA zones; the IANA name written is kept beside it
|
||||
(``HKLM:\\SOFTWARE\\napalm-windows``, ``IanaTimeZone``) and read back while the
|
||||
host is still in its Windows zone, so the zone reads back as written. A zone changed
|
||||
by hand since reads as its CLDR name.
|
||||
|
||||
Each write is skipped where the host already has what it would write.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin
|
||||
|
||||
from napalm_windows._powershell import _ps_quote
|
||||
from napalm_windows.time_zones import IANA_TO_WINDOWS, iana_time_zone, windows_time_zone
|
||||
|
||||
_W32TIME = r"HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters"
|
||||
_TZ_INFO = r"HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
|
||||
_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\W32Time\Parameters"
|
||||
#: Where the IANA name of the zone written is kept.
|
||||
MARKER_KEY = r"HKLM:\SOFTWARE\napalm-windows"
|
||||
#: w32time's modes that take time from the domain hierarchy.
|
||||
_DOMAIN_TYPES = frozenset({"nt5ds", "allsync"})
|
||||
|
||||
# w32tm runs inside cmd.exe with its stderr merged: in a remote session a line on
|
||||
# stderr would be an error record, and the whole reading would fail.
|
||||
_PS_TIME_SYNC = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function V($path, $name) {{
|
||||
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
|
||||
if ($item) {{ [string]$item.$name }}
|
||||
}}
|
||||
$svc = Get-Service -Name W32Time -ErrorAction SilentlyContinue
|
||||
$status = $null
|
||||
if ($svc -and [string]$svc.Status -eq 'Running') {{
|
||||
$status = @(cmd.exe /c 'w32tm /query /status 2>&1') -join "`n"
|
||||
}}
|
||||
[pscustomobject]@{{
|
||||
type = V '{_W32TIME}' 'Type'
|
||||
ntp_server = V '{_W32TIME}' 'NtpServer'
|
||||
policy_type = V '{_POLICY}' 'Type'
|
||||
policy_server = V '{_POLICY}' 'NtpServer'
|
||||
service = if ($svc) {{ [string]$svc.Status }} else {{ $null }}
|
||||
status = $status
|
||||
zone = V '{_TZ_INFO}' 'TimeZoneKeyName'
|
||||
dst_off = V '{_TZ_INFO}' 'DynamicDaylightTimeDisabled'
|
||||
iana_zone = V '{MARKER_KEY}' 'IanaTimeZone'
|
||||
}} | ConvertTo-Json -Compress
|
||||
"""
|
||||
|
||||
_PS_SET_SERVERS = f"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-ItemProperty -Path '{_W32TIME}' -Name NtpServer -Value {{peers}}
|
||||
Set-ItemProperty -Path '{_W32TIME}' -Name Type -Value 'NTP'
|
||||
if ([string](Get-Service -Name W32Time).Status -ne 'Running') {{{{ Start-Service -Name W32Time }}}}
|
||||
$out = @(cmd.exe /c 'w32tm /config /update 2>&1')
|
||||
if ($LASTEXITCODE -ne 0) {{{{ throw ('w32tm /config /update: ' + ($out -join ' ')) }}}}
|
||||
"""
|
||||
|
||||
_PS_SET_ZONE = """
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-TimeZone -Id {windows}
|
||||
"""
|
||||
|
||||
_PS_MARK_ZONE = """
|
||||
if (-not (Test-Path -Path '{key}')) {{ New-Item -Path '{key}' | Out-Null }}
|
||||
Set-ItemProperty -Path '{key}' -Name IanaTimeZone -Value {zone}
|
||||
"""
|
||||
|
||||
_LEAP = re.compile(r":\s*([0-3])\b")
|
||||
|
||||
|
||||
def _servers(value: str | None) -> list[str]:
|
||||
"""``NtpServer``'s names in order, without their ``,0xFLAGS``, each once."""
|
||||
names: list[str] = []
|
||||
for entry in (value or "").split():
|
||||
name = entry.split(",", 1)[0].strip()
|
||||
if name and name.lower() not in (n.lower() for n in names):
|
||||
names.append(name)
|
||||
return names
|
||||
|
||||
|
||||
def _synchronized(service: str | None, status: str | None) -> bool | None:
|
||||
"""The leap indicator, the first line of ``w32tm /query /status``: 3 is unsynchronised."""
|
||||
if service is None:
|
||||
return None
|
||||
if service.lower() != "running":
|
||||
return False
|
||||
first = (status or "").strip().splitlines()[:1]
|
||||
match = _LEAP.search(first[0]) if first else None
|
||||
return None if match is None else match.group(1) != "3"
|
||||
|
||||
|
||||
def _windows_zone(raw: dict[str, Any]) -> str:
|
||||
"""``TimeZoneKeyName``, which older Windows pad with NULs."""
|
||||
return str(raw.get("zone") or "").split("\x00", 1)[0].strip()
|
||||
|
||||
|
||||
def _time_zone(raw: dict[str, Any]) -> str | None:
|
||||
"""The host's zone as an IANA name: the one written while the host keeps its Windows
|
||||
zone, else CLDR's; None for summer time switched off or a zone not in the table."""
|
||||
windows, marker = _windows_zone(raw), str(raw.get("iana_zone") or "")
|
||||
if not windows or str(raw.get("dst_off") or "0").strip() != "0":
|
||||
return None
|
||||
if marker and IANA_TO_WINDOWS.get(marker) == windows:
|
||||
return marker
|
||||
return iana_time_zone(windows)
|
||||
|
||||
|
||||
class _Reading:
|
||||
"""What the reading script said, with group policy applied."""
|
||||
|
||||
def __init__(self, raw: dict[str, Any]) -> None:
|
||||
self.raw = raw
|
||||
self.by_policy = bool(raw.get("policy_type") or raw.get("policy_server"))
|
||||
self.type = str(raw.get("policy_type") or raw.get("type") or "").strip().lower()
|
||||
self.servers = _servers(raw.get("policy_server") or raw.get("ntp_server"))
|
||||
|
||||
def time_sync(self) -> TimeSyncDict:
|
||||
return {
|
||||
"ntp_servers": [] if self.type == "nosync" else self.servers,
|
||||
"timezone": _time_zone(self.raw),
|
||||
"synchronized": _synchronized(self.raw.get("service"), self.raw.get("status")),
|
||||
"daemon": "w32time",
|
||||
}
|
||||
|
||||
|
||||
class WindowsTimeSyncMixin(TimeSyncMixin):
|
||||
"""w32time's servers and the time zone; the driver carries the scripts."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def _ts_read(self) -> _Reading:
|
||||
out = self._run_raw(_PS_TIME_SYNC).strip()
|
||||
raw = json.loads(out) if out else None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("the time sync reading came back empty")
|
||||
return _Reading(raw)
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""w32time's servers, whether it is synchronised, and the zone; one round trip.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return self._ts_read().time_sync()
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
"""``w32tm /config`` with *servers* as manual peers; see the module."""
|
||||
now = self._ts_read()
|
||||
if now.by_policy:
|
||||
return {
|
||||
"ok": False,
|
||||
"output": "the Windows Time settings come from group policy; "
|
||||
"they are changed there, not on the host",
|
||||
}
|
||||
if now.type in _DOMAIN_TYPES:
|
||||
return {
|
||||
"ok": False,
|
||||
"output": "the host takes its time from the domain hierarchy "
|
||||
f"(w32time Type {now.raw.get('type')}); the domain sets its time sources",
|
||||
}
|
||||
if now.type == "ntp" and [s.lower() for s in now.servers] == [s.lower() for s in servers]:
|
||||
return {"ok": True, "output": "w32time already has these servers"}
|
||||
peers = " ".join(f"{server},0x8" for server in servers)
|
||||
self._run_raw(_PS_SET_SERVERS.format(peers=_ps_quote(peers)))
|
||||
return {"ok": True, "output": f"w32time set to {', '.join(servers)}"}
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
"""``Set-TimeZone`` to *zone*'s Windows zone, and *zone* kept beside it; see the module."""
|
||||
windows = windows_time_zone(zone)
|
||||
if windows is None:
|
||||
return {"ok": False, "output": f"there is no Windows time zone for {zone}"}
|
||||
now = self._ts_read().raw
|
||||
script = ""
|
||||
if _windows_zone(now) != windows or str(now.get("dst_off") or "0").strip() != "0":
|
||||
script += _PS_SET_ZONE.format(windows=_ps_quote(windows))
|
||||
if script or now.get("iana_zone") != zone:
|
||||
script += _PS_MARK_ZONE.format(key=MARKER_KEY, zone=_ps_quote(zone))
|
||||
if not script:
|
||||
return {"ok": True, "output": f"the host is in {zone} already"}
|
||||
self._run_raw(script)
|
||||
return {"ok": True, "output": f"time zone set to {windows} ({zone})"}
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Windows time zone ids and IANA names, both ways.
|
||||
|
||||
Windows names its zones by their standard-time name (``W. Europe Standard Time``);
|
||||
the contracts want an IANA name. The tables are CLDR's ``windowsZones.xml``,
|
||||
generated into :mod:`napalm_windows._windows_zones` by ``tools/windows_zones.py``
|
||||
and never fetched at runtime:
|
||||
|
||||
* reading, a Windows zone is the zone CLDR names for its territory ``001`` -- one
|
||||
of several a Windows zone stands for (``W. Europe Standard Time`` is Berlin,
|
||||
Vienna, Rome, ...). A zone not in the table is ``None``: the reading says it does
|
||||
not know rather than guess;
|
||||
* writing, every IANA name CLDR maps, and the tzdata links to and from them, has
|
||||
its Windows zone.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_windows._windows_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA
|
||||
|
||||
|
||||
def iana_time_zone(windows_id: str | None) -> str | None:
|
||||
"""The IANA name of the Windows zone *windows_id*; None for one the table lacks."""
|
||||
return WINDOWS_TO_IANA.get(windows_id or "")
|
||||
|
||||
|
||||
def windows_time_zone(iana: str | None) -> str | None:
|
||||
"""The Windows zone that keeps the IANA zone *iana*; None for one Windows lacks."""
|
||||
return IANA_TO_WINDOWS.get(iana or "")
|
||||
|
||||
|
||||
__all__ = ["IANA_TO_WINDOWS", "WINDOWS_TO_IANA", "iana_time_zone", "windows_time_zone"]
|
||||
@@ -104,6 +104,22 @@ class PsrpTransport:
|
||||
raise PowerShellError(message or "PowerShell reported an error")
|
||||
return "\n".join(str(o) for o in output if o is not None)
|
||||
|
||||
def run_last(self, script: str) -> bool:
|
||||
"""Run a script after which the host may stop answering: a restart, a shutdown.
|
||||
|
||||
True when the script finished. False when the connection broke before the
|
||||
answer came, which for such a script means the host went down first; the
|
||||
transport is closed then. An error the script wrote still raises
|
||||
:class:`PowerShellError`: the host answered, and refused.
|
||||
"""
|
||||
try:
|
||||
self.run(script)
|
||||
except (requests.RequestException, WinRMError, OSError) as exc:
|
||||
logger.debug("Connection to %s broke during its last script: %s", self.host, exc)
|
||||
self._drop()
|
||||
return False
|
||||
return True
|
||||
|
||||
def close(self) -> None:
|
||||
if self._pool is not None:
|
||||
try:
|
||||
|
||||
+45
-21
@@ -26,6 +26,10 @@ 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_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
|
||||
from napalm_windows.storage import WindowsStorageMixin
|
||||
from napalm_windows.time_sync import WindowsTimeSyncMixin
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -178,13 +182,16 @@ _SERVICE_COMMANDS = {
|
||||
"disable": "Set-Service -Name {name} -StartupType Disabled",
|
||||
}
|
||||
|
||||
# The host's own restart and shutdown, without -Force: Windows asks running programs to
|
||||
# close and refuses while other users are logged on, instead of throwing away what they
|
||||
# have not saved. Both start the shutdown and return; WinRM goes later, with the services.
|
||||
_PS_REBOOT = "Restart-Computer -Confirm:$false -ErrorAction Stop"
|
||||
_PS_SHUTDOWN = "Stop-Computer -Confirm:$false -ErrorAction Stop"
|
||||
|
||||
# Service key names, not display names: letters, digits and the few symbols
|
||||
# real services use (MSSQL$SQLEXPRESS, CDPUserSvc_4a5b6, {GUID}-style names).
|
||||
_SERVICE_NAME_RE = re.compile(r"^[\w.$@{}\-]+$", re.ASCII)
|
||||
|
||||
# PowerShell accepts these as single-quote delimiters alongside the ASCII one.
|
||||
_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛")
|
||||
|
||||
_ROUTE_PROTOCOLS = {
|
||||
"local": "connected",
|
||||
"routeradvertisement": "connected",
|
||||
@@ -204,22 +211,6 @@ _DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[Any]:
|
||||
"""Undo ConvertTo-Json unwrapping a one-element array into a bare value."""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
return [value]
|
||||
|
||||
|
||||
def _ps_quote(value: str) -> str:
|
||||
"""Quote ``value`` as a PowerShell single-quoted (verbatim) string."""
|
||||
for q in _PS_SINGLE_QUOTES:
|
||||
value = value.replace(q, q + q)
|
||||
return f"'{value}'"
|
||||
|
||||
|
||||
def _mac(value: str | None) -> str:
|
||||
"""``00-15-5d-01-02-03`` → ``00:15:5D:01:02:03``."""
|
||||
if not value:
|
||||
@@ -271,7 +262,7 @@ def _is_noise_route(destination: str) -> bool:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsDriver(OSDriver):
|
||||
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsStorageMixin, OSDriver):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
``optional_args``:
|
||||
@@ -369,6 +360,15 @@ class WindowsDriver(OSDriver):
|
||||
raise ConnectionClosedException("WinRM connection is not open")
|
||||
return self._transport.run(script)
|
||||
|
||||
def _run_power(self, script: str, what: str) -> None:
|
||||
"""Send a restart or shutdown; the connection the host drops counts as accepted."""
|
||||
if self._transport is None:
|
||||
raise ConnectionClosedException("WinRM connection is not open")
|
||||
try:
|
||||
self._transport.run_last(script)
|
||||
except PowerShellError as exc:
|
||||
raise RuntimeError(f"The host refused to {what}: {exc}") from exc
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# NAPALM getters
|
||||
# ------------------------------------------------------------------
|
||||
@@ -436,6 +436,8 @@ class WindowsDriver(OSDriver):
|
||||
return result
|
||||
|
||||
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
|
||||
"""Get-NetNeighbor's IPv4 neighbours. It reports a state but no age, so
|
||||
``age`` is ``-1.0`` (unknown, napalm-device-types' ``ARP_AGE_UNKNOWN``)."""
|
||||
entries = []
|
||||
for n in _as_list(self._run_ps(_PS_ARP)):
|
||||
if (n.get("state") or "").lower() in _DEAD_NEIGHBOUR_STATES:
|
||||
@@ -443,7 +445,7 @@ class WindowsDriver(OSDriver):
|
||||
mac = _mac(n.get("mac"))
|
||||
if not _is_real_neighbour_mac(mac):
|
||||
continue
|
||||
entries.append({"interface": n["interface"], "mac": mac, "ip": n["ip"], "age": 0.0})
|
||||
entries.append({"interface": n["interface"], "mac": mac, "ip": n["ip"], "age": -1.0})
|
||||
return entries
|
||||
|
||||
def get_route_to(
|
||||
@@ -520,6 +522,28 @@ class WindowsDriver(OSDriver):
|
||||
sockets.sort(key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or ""))
|
||||
return {"attributed": True, "sockets": sockets}
|
||||
|
||||
def reboot_host(self) -> None:
|
||||
"""Restart the host cleanly (``HostRebootMixin``) with ``Restart-Computer``.
|
||||
|
||||
Not forced: programs are asked to close, and Windows refuses while other users
|
||||
are logged on, a disconnected session included. Returns once the restart is
|
||||
under way; a connection the host drops before answering counts as that.
|
||||
|
||||
:raises RuntimeError: when the host refuses, with its answer.
|
||||
"""
|
||||
self._run_power(_PS_REBOOT, "restart")
|
||||
|
||||
def shutdown_host(self) -> None:
|
||||
"""Shut the host down cleanly and power it off (``HostShutdownMixin``) with
|
||||
``Stop-Computer``.
|
||||
|
||||
Not forced, as :meth:`reboot_host`. Returns once the shutdown is under way; a
|
||||
connection the host drops before answering counts as that.
|
||||
|
||||
:raises RuntimeError: when the host refuses, with its answer.
|
||||
"""
|
||||
self._run_power(_PS_SHUTDOWN, "shut down")
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]:
|
||||
template = _SERVICE_COMMANDS.get(action)
|
||||
if template is None:
|
||||
|
||||
+5
-7
@@ -7,7 +7,7 @@ name = "napalm-windows"
|
||||
version = "0.2.0"
|
||||
description = "NAPALM driver for Windows hosts via PowerShell Remoting (WinRM)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
requires-python = ">=3.12"
|
||||
license = "Apache-2.0"
|
||||
authors = [
|
||||
{ name = "Christian Manivong", email = "christian@manivong.de" },
|
||||
@@ -28,8 +28,6 @@ classifiers = [
|
||||
"Intended Audience :: System Administrators",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: System :: Networking",
|
||||
@@ -37,8 +35,8 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=4.21.1",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.35.0", # TimeSyncMixin
|
||||
"pypsrp>=0.8",
|
||||
]
|
||||
|
||||
@@ -67,7 +65,7 @@ napalm_windows = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
@@ -77,7 +75,7 @@ select = ["E", "F", "I", "UP", "B"]
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
{
|
||||
"time_zone": "W. Europe Standard Time",
|
||||
"count": 5,
|
||||
"tasks": [
|
||||
{
|
||||
"path": "\\Microsoft\\Windows\\Defrag\\",
|
||||
"name": "ScheduledDefrag",
|
||||
"state": "Ready",
|
||||
"user": "SYSTEM",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": "This task optimizes local storage drives.",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "%windir%\\system32\\defrag.exe", "arguments": "-c -h -o -$", "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskWeeklyTrigger", "enabled": true, "start": "2026-01-01T01:00:00", "days_interval": null, "weeks_interval": 1, "days_of_week": 1, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "2026-11-01T00:00:12.0000000Z",
|
||||
"last_result": 0,
|
||||
"next_run": "2026-11-08T00:00:00.0000000Z"
|
||||
},
|
||||
{
|
||||
"path": "\\Microsoft\\Windows\\UpdateOrchestrator\\",
|
||||
"name": "Reboot",
|
||||
"state": "Disabled",
|
||||
"user": "SYSTEM",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": null,
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "%systemroot%\\system32\\MusNotification.exe", "arguments": "RebootDialog", "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskTimeTrigger", "enabled": true, "start": "2026-11-04T03:00:00+01:00", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "1999-11-29T23:00:00.0000000Z",
|
||||
"last_result": 267011,
|
||||
"next_run": null
|
||||
},
|
||||
{
|
||||
"path": "\\",
|
||||
"name": "Admin's backup",
|
||||
"state": "Ready",
|
||||
"user": "Administrator",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": "Copies D:\\data to the NAS",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "robocopy.exe", "arguments": "D:\\data \\\\nas\\backup /MIR", "class_id": null},
|
||||
{"class": "MSFT_TaskExecAction", "execute": "C:\\scripts\\notify.cmd", "arguments": null, "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskDailyTrigger", "enabled": true, "start": "2026-01-01T00:00:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "PT1H", "duration": "P1D", "delay": ""},
|
||||
{"class": "MSFT_TaskDailyTrigger", "enabled": false, "start": "2026-01-01T12:30:00", "days_interval": 2, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "/Date(1793854800000)/",
|
||||
"last_result": 2147942402,
|
||||
"next_run": "/Date(1793858400000)/"
|
||||
},
|
||||
{
|
||||
"path": "\\",
|
||||
"name": "nightly-dump",
|
||||
"state": "Ready",
|
||||
"user": "backup",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": "napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "%SystemRoot%\\System32\\cmd.exe", "arguments": "/d /s /c \"pg_dump -f D:\\dump.sql app\"", "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskTrigger", "enabled": true, "start": "2020-01-01T02:30:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "2026-11-03T01:30:04.1234567Z",
|
||||
"last_result": 1,
|
||||
"next_run": "2026-11-04T01:30:00Z"
|
||||
},
|
||||
{
|
||||
"path": "\\Vendor\\",
|
||||
"name": "Updater",
|
||||
"state": "Running",
|
||||
"user": null,
|
||||
"group": "Users",
|
||||
"on_demand": false,
|
||||
"description": "",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskComHandlerAction", "execute": null, "arguments": null, "class_id": "{A6BA00FE-40E8-477C-B713-C64A14F18ADB}"}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskLogonTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": "PT15M"},
|
||||
{"class": "MSFT_TaskBootTrigger", "enabled": null, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""},
|
||||
{"class": "MSFT_TaskSessionStateChangeTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "2026-11-03T06:00:00Z",
|
||||
"last_result": 267009,
|
||||
"next_run": null
|
||||
}
|
||||
]
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"type":"NTP","ntp_server":"time.windows.com,0x9","policy_type":null,"policy_server":null,"service":"Running","status":"Leap Indicator: 0(no warning)\nStratum: 4 (secondary reference - syncd by (S)NTP)\nPrecision: -23 (119.209ns per tick)\nRoot Delay: 0.0312500s\nRoot Dispersion: 7.9876543s\nReferenceId: 0x14650039 (source IP: 20.101.57.9)\nLast Successful Sync Time: 11/11/2026 10:00:00 AM\nSource: time.windows.com,0x9\nPoll Interval: 10 (1024s)\n","zone":"W. Europe Standard Time","dst_off":"0","iana_zone":null}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"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,639 @@
|
||||
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
|
||||
|
||||
The reading is one script whose JSON a fake transport answers from
|
||||
tests/fixtures/synthetic/scheduled_tasks.json; every write is one script, read
|
||||
here as text. What a real host does with those scripts the fixtures cannot
|
||||
prove -- see the README there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import (
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobsMixin,
|
||||
job_digest,
|
||||
)
|
||||
|
||||
from napalm_windows import WindowsDriver, task_xml
|
||||
from napalm_windows import scheduled_tasks as mod
|
||||
from napalm_windows.time_zones import iana_time_zone
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "scheduled_tasks.json"
|
||||
|
||||
DEFRAG = "task:\\Microsoft\\Windows\\Defrag\\ScheduledDefrag"
|
||||
REBOOT = "task:\\Microsoft\\Windows\\UpdateOrchestrator\\Reboot"
|
||||
BACKUP = "task:\\Admin's backup"
|
||||
DUMP = "task:\\nightly-dump"
|
||||
UPDATER = "task:\\Vendor\\Updater"
|
||||
|
||||
|
||||
def _reading() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""Answers the reading script with *reading*; records every other script."""
|
||||
|
||||
def __init__(self, reading: Any, fail: str | None = None):
|
||||
self.reading = reading
|
||||
self.fail = fail
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
if script == mod._PS_SCHEDULED_TASKS:
|
||||
return self.reading if isinstance(self.reading, str) else json.dumps(self.reading)
|
||||
if self.fail:
|
||||
raise PowerShellError(self.fail)
|
||||
return ""
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
@property
|
||||
def writes(self) -> list[str]:
|
||||
return [s for s in self.sent if s != mod._PS_SCHEDULED_TASKS]
|
||||
|
||||
|
||||
def _driver(reading: Any = None, fail: str | None = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(_reading() if reading is None else reading, fail) # type: ignore[assignment]
|
||||
return d
|
||||
|
||||
|
||||
def _jobs(reading: Any = None) -> dict[str, dict[str, Any]]:
|
||||
return {j["key"]: dict(j) for j in _driver(reading).get_scheduled_jobs()["jobs"]}
|
||||
|
||||
|
||||
def _digest(key: str, reading: Any = None) -> str:
|
||||
return str(_jobs(reading)[key]["digest"])
|
||||
|
||||
|
||||
def _spec(**changes: Any) -> dict[str, Any]:
|
||||
spec = {
|
||||
"name": "nightly-dump",
|
||||
"schedule": "30 2 * * *",
|
||||
"run_as": "backup",
|
||||
"command": "pg_dump -f D:\\dump.sql app",
|
||||
"enabled": True,
|
||||
"description": "Dump the database",
|
||||
}
|
||||
spec.update(changes)
|
||||
return spec
|
||||
|
||||
|
||||
def _without_dump() -> dict[str, Any]:
|
||||
reading = _reading()
|
||||
reading["tasks"] = [t for t in reading["tasks"] if t["name"] != "nightly-dump"]
|
||||
reading["count"] = len(reading["tasks"])
|
||||
return reading
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_windows_host_offers_every_verb():
|
||||
assert issubclass(WindowsDriver, ScheduledJobsMixin)
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
):
|
||||
assert callable(getattr(WindowsDriver, verb))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestReading:
|
||||
def test_every_task_in_one_round_trip(self):
|
||||
d = _driver()
|
||||
|
||||
reading = d.get_scheduled_jobs()
|
||||
|
||||
assert len(reading["jobs"]) == 5
|
||||
assert d._transport.sent == [mod._PS_SCHEDULED_TASKS]
|
||||
|
||||
def test_the_script_joins_the_task_and_its_run_info_and_changes_nothing(self):
|
||||
script = mod._PS_SCHEDULED_TASKS
|
||||
assert "Get-ScheduledTask" in script
|
||||
assert "Get-ScheduledTaskInfo" in script
|
||||
assert "ConvertTo-Json" in script
|
||||
for verb in ("Set-", "Register-", "Unregister-", "Enable-", "Disable-", "Start-"):
|
||||
assert verb not in script
|
||||
|
||||
def test_a_platform_task(self):
|
||||
job = _jobs()[DEFRAG]
|
||||
|
||||
assert {k: job[k] for k in job if k != "digest"} == {
|
||||
"key": DEFRAG,
|
||||
"kind": "task",
|
||||
"source": "\\Microsoft\\Windows\\Defrag\\ScheduledDefrag",
|
||||
"run_as": "SYSTEM",
|
||||
"schedule": "weekly on Sun at 01:00",
|
||||
"schedule_kind": "triggers",
|
||||
"command": "%windir%\\system32\\defrag.exe -c -h -o -$",
|
||||
"enabled": True,
|
||||
"managed_by": "platform",
|
||||
"actions": ["enable", "disable", "run"],
|
||||
"description": "This task optimizes local storage drives.",
|
||||
"last_run": "2026-11-01T00:00:12+00:00",
|
||||
"last_result": "success",
|
||||
"next_run": "2026-11-08T00:00:00+00:00",
|
||||
}
|
||||
|
||||
def test_the_digest_is_the_contracts(self):
|
||||
job = _jobs()[DEFRAG]
|
||||
|
||||
assert job["digest"] == job_digest(job)
|
||||
|
||||
def test_a_disabled_task_is_not_enabled_and_cannot_be_run(self):
|
||||
job = _jobs()[REBOOT]
|
||||
|
||||
assert job["enabled"] is False
|
||||
assert job["actions"] == ["enable", "disable"]
|
||||
|
||||
def test_a_task_that_never_ran_has_no_last_run_or_result(self):
|
||||
"""Task Scheduler says 30 November 1999 for never, and 0x41303 for its result."""
|
||||
job = _jobs()[REBOOT]
|
||||
|
||||
assert (job["last_run"], job["last_result"], job["next_run"]) == (None, None, None)
|
||||
|
||||
def test_a_task_without_a_description_has_none(self):
|
||||
assert "description" not in _jobs()[REBOOT]
|
||||
|
||||
def test_a_once_trigger_keeps_its_offset(self):
|
||||
assert _jobs()[REBOOT]["schedule"] == "once at 2026-11-04 03:00+01:00"
|
||||
|
||||
def test_an_admins_task_with_two_actions_and_two_triggers(self):
|
||||
job = _jobs()[BACKUP]
|
||||
|
||||
assert job["managed_by"] == "admin"
|
||||
assert job["run_as"] == "Administrator"
|
||||
assert (
|
||||
job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR\nC:\\scripts\\notify.cmd"
|
||||
)
|
||||
assert job["schedule"] == (
|
||||
"daily at 00:00, every 1 hour for 1 day; every 2 days at 12:30 (disabled)"
|
||||
)
|
||||
assert job["actions"] == ["enable", "disable", "run"]
|
||||
|
||||
def test_json_dates_are_iso_utc(self):
|
||||
job = _jobs()[BACKUP]
|
||||
|
||||
assert job["last_run"] == "2026-11-05T05:00:00+00:00"
|
||||
assert job["next_run"] == "2026-11-05T06:00:00+00:00"
|
||||
|
||||
def test_a_failure_code_is_hex(self):
|
||||
assert _jobs()[BACKUP]["last_result"] == "0x80070002"
|
||||
|
||||
def test_an_applications_task(self):
|
||||
job = _jobs()[DUMP]
|
||||
|
||||
assert job["managed_by"] == "application"
|
||||
assert job["name"] == "nightly-dump"
|
||||
assert job["description"] == "Dump the database"
|
||||
assert (job["schedule"], job["schedule_kind"]) == ("30 2 * * *", "cron")
|
||||
assert job["command"] == "pg_dump -f D:\\dump.sql app"
|
||||
assert job["run_as"] == "backup"
|
||||
assert job["actions"] == ["enable", "disable", "run", "edit", "delete"]
|
||||
assert job["last_result"] == "0x1"
|
||||
assert job["last_run"] == "2026-11-03T01:30:04.123456+00:00"
|
||||
|
||||
def test_an_applications_digest_covers_its_triggers(self):
|
||||
"""Triggers changed by hand change the digest, although the cron line stays."""
|
||||
changed = _reading()
|
||||
changed["tasks"][3]["triggers"][0]["start"] = "2020-01-01T03:30:00"
|
||||
|
||||
assert _digest(DUMP, changed) != _digest(DUMP)
|
||||
assert _jobs(changed)[DUMP]["schedule"] == "30 2 * * *"
|
||||
|
||||
def test_an_application_task_without_its_schedule_line_shows_its_triggers(self):
|
||||
reading = _reading()
|
||||
reading["tasks"][3]["description"] = "napalm-scheduled-job: nightly-dump"
|
||||
job = _jobs(reading)[DUMP]
|
||||
|
||||
assert (job["managed_by"], job["name"]) == ("application", "nightly-dump")
|
||||
assert "description" not in job
|
||||
assert (job["schedule"], job["schedule_kind"]) == ("trigger at 02:30", "triggers")
|
||||
|
||||
def test_an_application_task_whose_action_was_changed_shows_it(self):
|
||||
reading = _reading()
|
||||
reading["tasks"][3]["actions"][0]["arguments"] = "/c whoami"
|
||||
|
||||
assert _jobs(reading)[DUMP]["command"] == "%SystemRoot%\\System32\\cmd.exe /c whoami"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "name"),
|
||||
[("\\Vendor\\", "nightly-dump"), ("\\", "other-name"), ("\\", "Nightly Dump")],
|
||||
)
|
||||
def test_the_marker_counts_only_on_the_root_task_of_that_name(self, path, name):
|
||||
reading = _reading()
|
||||
reading["tasks"][3].update(path=path, name=name)
|
||||
|
||||
job = _jobs(reading)[f"task:{path}{name}"]
|
||||
|
||||
assert job["managed_by"] == "admin"
|
||||
assert "edit" not in job["actions"]
|
||||
assert "name" not in job
|
||||
|
||||
def test_a_group_principal_a_com_handler_and_event_triggers(self):
|
||||
job = _jobs()[UPDATER]
|
||||
|
||||
assert job["run_as"] == "Users"
|
||||
assert job["command"] == "COM handler {A6BA00FE-40E8-477C-B713-C64A14F18ADB}"
|
||||
assert job["schedule"] == "at logon after 15 minutes; at startup; session state change"
|
||||
assert job["enabled"] is True
|
||||
assert job["last_result"] == "running"
|
||||
|
||||
def test_a_task_that_cannot_be_started_on_demand_does_not_offer_run(self):
|
||||
assert _jobs()[UPDATER]["actions"] == ["enable", "disable"]
|
||||
|
||||
def test_the_time_zone_is_iana(self):
|
||||
assert _driver().get_scheduled_jobs()["time_zone"] == "Europe/Berlin"
|
||||
|
||||
def test_an_unknown_time_zone_is_none(self):
|
||||
reading = _reading()
|
||||
reading["time_zone"] = "Mars Standard Time"
|
||||
|
||||
assert _driver(reading).get_scheduled_jobs()["time_zone"] is None
|
||||
|
||||
def test_one_task_arrives_as_a_bare_object(self):
|
||||
"""ConvertTo-Json unwraps a one-element array, nested ones too."""
|
||||
task = _reading()["tasks"][2]
|
||||
task["actions"] = task["actions"][0]
|
||||
task["triggers"] = task["triggers"][0]
|
||||
reading = {"time_zone": "UTC", "count": 1, "tasks": task}
|
||||
|
||||
(job,) = _driver(reading).get_scheduled_jobs()["jobs"]
|
||||
|
||||
assert job["key"] == BACKUP
|
||||
assert job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR"
|
||||
assert job["schedule"] == "daily at 00:00, every 1 hour for 1 day"
|
||||
|
||||
def test_a_host_without_tasks(self):
|
||||
reading = {"time_zone": None, "count": 0, "tasks": None}
|
||||
|
||||
assert _driver(reading).get_scheduled_jobs() == {"jobs": [], "time_zone": None}
|
||||
|
||||
def test_a_reading_cut_short_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
_driver(json.dumps(_reading())[:-40]).get_scheduled_jobs()
|
||||
|
||||
def test_a_reading_with_fewer_tasks_than_counted_raises(self):
|
||||
reading = _reading()
|
||||
reading["count"] = 6
|
||||
|
||||
with pytest.raises(ValueError, match="6"):
|
||||
_driver(reading).get_scheduled_jobs()
|
||||
|
||||
def test_an_empty_answer_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
_driver("").get_scheduled_jobs()
|
||||
|
||||
def test_a_failed_reading_raises(self):
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(_reading()) # type: ignore[assignment]
|
||||
d._transport.reading = None
|
||||
d._transport.run = lambda script: (_ for _ in ()).throw(PowerShellError("Access denied")) # type: ignore[method-assign]
|
||||
|
||||
with pytest.raises(PowerShellError):
|
||||
d.get_scheduled_jobs()
|
||||
|
||||
|
||||
class TestOddTasks:
|
||||
def _job(self, **changes: Any) -> dict[str, Any]:
|
||||
task = _reading()["tasks"][0]
|
||||
task.update(changes)
|
||||
return _jobs({"time_zone": None, "count": 1, "tasks": [task]})[DEFRAG]
|
||||
|
||||
def test_an_action_without_a_command_or_handler_names_its_class(self):
|
||||
job = self._job(actions=[{"class": "MSFT_TaskSendEmailAction"}])
|
||||
|
||||
assert job["command"] == "MSFT_TaskSendEmailAction"
|
||||
|
||||
def test_a_start_and_delay_it_cannot_read_are_kept_as_they_are(self):
|
||||
trigger = {"class": "MSFT_TaskDailyTrigger", "start": "soon", "delay": "a while"}
|
||||
|
||||
assert self._job(triggers=[trigger])["schedule"] == "daily at soon after a while"
|
||||
|
||||
def test_a_task_that_never_ran_since_it_was_read_has_no_result(self):
|
||||
job = self._job(last_result=267011)
|
||||
|
||||
assert job["last_run"] is not None
|
||||
assert job["last_result"] is None
|
||||
|
||||
def test_a_negative_result_is_the_same_code(self):
|
||||
assert self._job(last_result=-2147024894)["last_result"] == "0x80070002"
|
||||
|
||||
def test_a_reading_that_is_not_an_object_raises(self):
|
||||
with pytest.raises(ValueError, match="reading"):
|
||||
_driver("[]").get_scheduled_jobs()
|
||||
|
||||
|
||||
class TestTimestamps:
|
||||
@pytest.mark.parametrize(
|
||||
("value", "iso"),
|
||||
[
|
||||
(None, None),
|
||||
("", None),
|
||||
("2026-11-03T01:30:00Z", "2026-11-03T01:30:00+00:00"),
|
||||
("2026-11-03T02:30:00+01:00", "2026-11-03T01:30:00+00:00"),
|
||||
("2026-11-03T01:30:00", "2026-11-03T01:30:00+00:00"),
|
||||
("/Date(1793854800000)/", "2026-11-05T05:00:00+00:00"),
|
||||
("/Date(1793854800000+0100)/", "2026-11-05T05:00:00+00:00"),
|
||||
(1793854800, "2026-11-05T05:00:00+00:00"),
|
||||
("1999-11-30T00:00:00", None),
|
||||
("/Date(943916400000)/", None),
|
||||
("not a date", None),
|
||||
],
|
||||
)
|
||||
def test_to_iso_utc(self, value, iso):
|
||||
assert mod._timestamp(value) == iso
|
||||
|
||||
|
||||
class TestTimeZones:
|
||||
@pytest.mark.parametrize(
|
||||
("windows", "iana"),
|
||||
[
|
||||
("W. Europe Standard Time", "Europe/Berlin"),
|
||||
("GMT Standard Time", "Europe/London"),
|
||||
("Eastern Standard Time", "America/New_York"),
|
||||
("UTC", "Etc/UTC"),
|
||||
("Tokyo Standard Time", "Asia/Tokyo"),
|
||||
("Mars Standard Time", None),
|
||||
(None, None),
|
||||
],
|
||||
)
|
||||
def test_a_windows_zone_id_as_iana(self, windows, iana):
|
||||
assert iana_time_zone(windows) == iana
|
||||
|
||||
def test_every_name_in_the_table_is_a_real_zone(self):
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from napalm_windows.time_zones import WINDOWS_TO_IANA
|
||||
|
||||
for name in WINDOWS_TO_IANA.values():
|
||||
ZoneInfo(name)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Enable, disable, run
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestManage:
|
||||
@pytest.mark.parametrize(
|
||||
("action", "cmdlet"),
|
||||
[("enable", "Enable-ScheduledTask"), ("disable", "Disable-ScheduledTask")],
|
||||
)
|
||||
def test_switches_the_tasks_own_flag(self, action, cmdlet):
|
||||
d = _driver()
|
||||
|
||||
result = d.manage_scheduled_job(DEFRAG, action, digest=_digest(DEFRAG))
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert cmdlet in script
|
||||
assert "'\\Microsoft\\Windows\\Defrag\\'" in script
|
||||
assert "'ScheduledDefrag'" in script
|
||||
assert result == {"success": True, "output": f"{DEFRAG} {action}d"}
|
||||
|
||||
def test_run_says_the_task_was_started_not_that_it_finished(self):
|
||||
d = _driver()
|
||||
|
||||
result = d.manage_scheduled_job(DEFRAG, "run", digest=_digest(DEFRAG))
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert "Start-ScheduledTask" in script
|
||||
assert result["success"] is True
|
||||
assert "started" in result["output"]
|
||||
assert "next reading" in result["output"]
|
||||
|
||||
def test_reads_again_before_it_writes(self):
|
||||
d = _driver()
|
||||
|
||||
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
|
||||
|
||||
assert d._transport.sent[0] == mod._PS_SCHEDULED_TASKS
|
||||
|
||||
def test_the_task_is_found_by_exact_path_and_name(self):
|
||||
"""Not by -TaskName, which takes wildcards."""
|
||||
d = _driver()
|
||||
|
||||
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
|
||||
|
||||
script = d._transport.writes[0]
|
||||
assert "-eq '\\Microsoft\\Windows\\Defrag\\'" in script
|
||||
assert "-eq 'ScheduledDefrag'" in script
|
||||
assert "-TaskName" not in script
|
||||
|
||||
def test_a_quote_in_a_task_name_is_doubled(self):
|
||||
d = _driver()
|
||||
|
||||
d.manage_scheduled_job(BACKUP, "disable", digest=_digest(BACKUP))
|
||||
|
||||
assert "'Admin''s backup'" in d._transport.writes[0]
|
||||
|
||||
def test_a_changed_task_is_not_switched(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
d.manage_scheduled_job(DEFRAG, "disable", digest="0" * 16)
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_an_unknown_task_raises_lookup_error(self):
|
||||
with pytest.raises(LookupError):
|
||||
_driver().manage_scheduled_job("task:\\nope", "run", digest="0" * 16)
|
||||
|
||||
def test_an_unknown_action_is_refused_before_anything_is_sent(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="action"):
|
||||
d.manage_scheduled_job(DEFRAG, "delete", digest=_digest(DEFRAG))
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_a_disabled_task_is_not_run(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="run"):
|
||||
d.manage_scheduled_job(REBOOT, "run", digest=_digest(REBOOT))
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_what_powershell_says_is_the_result(self):
|
||||
d = _driver(fail="Access is denied.")
|
||||
|
||||
result = d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
|
||||
|
||||
assert result == {"success": False, "output": "Access is denied."}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# An application's own task
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPut:
|
||||
def test_creates_the_task_in_the_root_folder_from_xml(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert "Register-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Xml '" in script
|
||||
assert "-Force" in script
|
||||
assert result == {"success": True, "output": f"{DUMP} created"}
|
||||
|
||||
def test_the_xml_carries_the_definition(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
|
||||
script = d._transport.writes[0]
|
||||
assert task_xml.task_xml(_spec()).replace("'", "''") in script # type: ignore[arg-type]
|
||||
|
||||
def test_a_task_of_that_name_there_already(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged, match="already"):
|
||||
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_an_admins_root_task_of_that_name_is_not_overwritten(self):
|
||||
reading = _reading()
|
||||
reading["tasks"][3]["description"] = "mine"
|
||||
|
||||
d = _driver(reading)
|
||||
with pytest.raises(ScheduledJobChanged, match="already"):
|
||||
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
with pytest.raises(ScheduledJobRefused, match="application"):
|
||||
d.put_scheduled_job(_spec(), digest=_digest(DUMP, reading)) # type: ignore[arg-type]
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_changes_its_own_task_with_the_digest_it_saw(self):
|
||||
d = _driver()
|
||||
|
||||
result = d.put_scheduled_job(_spec(schedule="*/5 * * * *"), digest=_digest(DUMP)) # type: ignore[arg-type]
|
||||
|
||||
assert "Register-ScheduledTask" in d._transport.writes[0]
|
||||
assert "<Interval>PT5M</Interval>" in d._transport.writes[0]
|
||||
assert result == {"success": True, "output": f"{DUMP} changed"}
|
||||
|
||||
def test_a_changed_task_is_not_overwritten(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_a_task_that_went_away_is_not_changed(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
with pytest.raises(LookupError):
|
||||
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
|
||||
|
||||
def test_a_spec_the_contract_refuses_is_refused_before_anything_is_sent(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="name"):
|
||||
d.put_scheduled_job(_spec(name="Nightly Dump")) # type: ignore[arg-type]
|
||||
assert d._transport.sent == []
|
||||
|
||||
def test_a_schedule_task_scheduler_cannot_take_is_refused_before_anything_is_sent(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="weekday"):
|
||||
d.put_scheduled_job(_spec(schedule="0 0 1 * 1")) # type: ignore[arg-type]
|
||||
assert d._transport.sent == []
|
||||
|
||||
def test_quotes_in_the_command_are_doubled_for_powershell(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
d.put_scheduled_job(_spec(command="echo it's done’")) # type: ignore[arg-type]
|
||||
|
||||
script = d._transport.writes[0]
|
||||
assert "echo it''s done’’" in script
|
||||
body = script.split("-Xml '", 1)[1].rsplit("' -Force", 1)[0]
|
||||
for quote in ("'", "‘", "’", "‚", "‛"):
|
||||
assert quote not in body.replace(quote * 2, "")
|
||||
|
||||
def test_what_powershell_says_is_the_result(self):
|
||||
d = _driver(_without_dump(), fail="The user name or password is incorrect.")
|
||||
|
||||
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
|
||||
assert result == {"success": False, "output": "The user name or password is incorrect."}
|
||||
|
||||
|
||||
class TestDelete:
|
||||
def test_unregisters_its_own_task(self):
|
||||
d = _driver()
|
||||
|
||||
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert (
|
||||
"Unregister-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Confirm:$false"
|
||||
in script
|
||||
)
|
||||
assert result == {"success": True, "output": f"{DUMP} deleted"}
|
||||
|
||||
@pytest.mark.parametrize("key", [DEFRAG, BACKUP])
|
||||
def test_a_task_an_application_did_not_write_is_refused(self, key):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="application"):
|
||||
d.delete_scheduled_job(key, digest=_digest(key))
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_a_changed_task_is_not_deleted(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
d.delete_scheduled_job(DUMP, digest="0" * 16)
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_an_unknown_task_raises_lookup_error(self):
|
||||
with pytest.raises(LookupError):
|
||||
_driver().delete_scheduled_job("task:\\nope", digest="0" * 16)
|
||||
|
||||
def test_what_powershell_says_is_the_result(self):
|
||||
d = _driver(fail="Access is denied.")
|
||||
|
||||
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
|
||||
|
||||
assert result == {"success": False, "output": "Access is denied."}
|
||||
|
||||
|
||||
def test_a_written_task_reads_back_as_the_spec():
|
||||
"""What put writes, the reading parses back to the same cron line and command."""
|
||||
spec = _spec(command='"C:\\Program Files\\app\\run.exe" --quiet & echo done')
|
||||
xml = task_xml.task_xml(spec) # type: ignore[arg-type]
|
||||
execute, arguments = task_xml.command_action(spec["command"])
|
||||
reading = _reading()
|
||||
task = copy.deepcopy(reading["tasks"][3])
|
||||
task["actions"] = [{"class": "MSFT_TaskExecAction", "execute": execute, "arguments": arguments}]
|
||||
task["description"] = task_xml.description(spec) # type: ignore[arg-type]
|
||||
reading["tasks"][3] = task
|
||||
|
||||
job = _jobs(reading)[DUMP]
|
||||
|
||||
assert (job["command"], job["schedule"], job["description"]) == (
|
||||
spec["command"],
|
||||
spec["schedule"],
|
||||
spec["description"],
|
||||
)
|
||||
assert f"<Command>{execute}</Command>" in xml
|
||||
@@ -0,0 +1,317 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,260 @@
|
||||
"""An application's task as Task Scheduler XML, and a cron expression as its triggers (#8).
|
||||
|
||||
A cron shape Task Scheduler can express exactly becomes triggers; every other
|
||||
shape is refused, naming why.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET # noqa: S405 - parses only what the tests built
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import ScheduledJobRefused
|
||||
|
||||
from napalm_windows import task_xml
|
||||
|
||||
NS = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
|
||||
|
||||
|
||||
def _spec(**changes: Any) -> Any:
|
||||
spec = {
|
||||
"name": "nightly-dump",
|
||||
"schedule": "30 2 * * *",
|
||||
"run_as": "backup",
|
||||
"command": "pg_dump -f D:\\dump.sql app",
|
||||
"enabled": True,
|
||||
"description": "Dump the database",
|
||||
}
|
||||
spec.update(changes)
|
||||
return spec
|
||||
|
||||
|
||||
def _task(**changes: Any) -> ET.Element:
|
||||
return ET.fromstring(task_xml.task_xml(_spec(**changes))) # noqa: S314
|
||||
|
||||
|
||||
def _text(task: ET.Element, path: str) -> str | None:
|
||||
found = task.find(path, NS)
|
||||
return None if found is None else found.text
|
||||
|
||||
|
||||
def _triggers(schedule: str) -> list[dict[str, Any]]:
|
||||
"""Each trigger as start, repetition and day schedule, for comparing."""
|
||||
triggers = []
|
||||
found = _task(schedule=schedule).find("t:Triggers", NS)
|
||||
assert found is not None
|
||||
for trigger in found:
|
||||
tag = trigger.tag.split("}")[1]
|
||||
entry: dict[str, Any] = {"type": tag}
|
||||
if tag == "CalendarTrigger":
|
||||
entry["start"] = _text(trigger, "t:StartBoundary")
|
||||
entry["repeat"] = (
|
||||
_text(trigger, "t:Repetition/t:Interval"),
|
||||
_text(trigger, "t:Repetition/t:Duration"),
|
||||
)
|
||||
schedule_by = next(c for c in trigger if c.tag.split("}")[1].startswith("Schedule"))
|
||||
entry["by"] = schedule_by.tag.split("}")[1]
|
||||
entry["days"] = [d.text for d in schedule_by.iter(f"{{{NS['t']}}}Day")]
|
||||
entry["names"] = [
|
||||
c.tag.split("}")[1]
|
||||
for part in ("DaysOfWeek", "Months")
|
||||
for parent in schedule_by.iter(f"{{{NS['t']}}}{part}")
|
||||
for c in parent
|
||||
]
|
||||
triggers.append(entry)
|
||||
return triggers
|
||||
|
||||
|
||||
class TestTriggers:
|
||||
def test_daily_at_one_time(self):
|
||||
assert _triggers("30 2 * * *") == [
|
||||
{
|
||||
"type": "CalendarTrigger",
|
||||
"start": "2020-01-01T02:30:00",
|
||||
"repeat": (None, None),
|
||||
"by": "ScheduleByDay",
|
||||
"days": [],
|
||||
"names": [],
|
||||
}
|
||||
]
|
||||
|
||||
def test_the_daily_alias(self):
|
||||
assert [t["start"] for t in _triggers("@daily")] == ["2020-01-01T00:00:00"]
|
||||
|
||||
def test_weekdays_at_two_times_are_two_weekly_triggers(self):
|
||||
triggers = _triggers("0 8,17 * * 1-5")
|
||||
|
||||
assert [t["start"] for t in triggers] == ["2020-01-01T08:00:00", "2020-01-01T17:00:00"]
|
||||
assert {t["by"] for t in triggers} == {"ScheduleByWeek"}
|
||||
assert triggers[0]["names"] == ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
|
||||
|
||||
def test_sunday_is_0_and_7(self):
|
||||
assert _triggers("0 0 * * 0")[0]["names"] == _triggers("0 0 * * 7")[0]["names"]
|
||||
assert _triggers("0 0 * * 7")[0]["names"] == ["Sunday"]
|
||||
|
||||
def test_every_five_minutes_is_one_repetition(self):
|
||||
assert _triggers("*/5 * * * *") == [
|
||||
{
|
||||
"type": "CalendarTrigger",
|
||||
"start": "2020-01-01T00:00:00",
|
||||
"repeat": ("PT5M", "PT23H56M"),
|
||||
"by": "ScheduleByDay",
|
||||
"days": [],
|
||||
"names": [],
|
||||
}
|
||||
]
|
||||
|
||||
def test_every_quarter_hour_in_working_hours(self):
|
||||
(trigger,) = _triggers("*/15 8-17 * * 1-5")
|
||||
|
||||
assert (trigger["start"], trigger["repeat"]) == (
|
||||
"2020-01-01T08:00:00",
|
||||
("PT15M", "PT9H46M"),
|
||||
)
|
||||
assert trigger["by"] == "ScheduleByWeek"
|
||||
|
||||
def test_every_six_hours(self):
|
||||
(trigger,) = _triggers("0 */6 * * *")
|
||||
|
||||
assert trigger["repeat"] == ("PT6H", "PT18H1M")
|
||||
|
||||
def test_every_minute(self):
|
||||
(trigger,) = _triggers("* * * * *")
|
||||
|
||||
assert (trigger["start"], trigger["repeat"]) == ("2020-01-01T00:00:00", ("PT1M", "PT24H"))
|
||||
|
||||
def test_a_step_that_does_not_divide_the_hour_repeats_within_each_hour(self):
|
||||
"""*/7 fires at :56 and then at :00 -- four minutes, not seven: one repetition per hour."""
|
||||
triggers = _triggers("*/7 * * * *")
|
||||
|
||||
assert len(triggers) == 24
|
||||
assert triggers[1]["start"] == "2020-01-01T01:00:00"
|
||||
assert {t["repeat"] for t in triggers} == {("PT7M", "PT57M")}
|
||||
|
||||
def test_two_hours_of_every_other_minute(self):
|
||||
triggers = _triggers("*/2 8,17 * * *")
|
||||
|
||||
assert [(t["start"], t["repeat"]) for t in triggers] == [
|
||||
("2020-01-01T08:00:00", ("PT2M", "PT59M")),
|
||||
("2020-01-01T17:00:00", ("PT2M", "PT59M")),
|
||||
]
|
||||
|
||||
def test_days_of_the_month(self):
|
||||
(trigger,) = _triggers("0 3 1,15 * *")
|
||||
|
||||
assert (trigger["by"], trigger["days"]) == ("ScheduleByMonth", ["1", "15"])
|
||||
assert len(trigger["names"]) == 12
|
||||
|
||||
def test_some_months_only(self):
|
||||
(trigger,) = _triggers("0 0 * 1,jul *")
|
||||
|
||||
assert trigger["by"] == "ScheduleByMonth"
|
||||
assert trigger["days"] == [str(d) for d in range(1, 32)]
|
||||
assert trigger["names"] == ["January", "July"]
|
||||
|
||||
def test_reboot_is_a_boot_trigger(self):
|
||||
assert _triggers("@reboot") == [{"type": "BootTrigger"}]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("schedule", "why"),
|
||||
[
|
||||
("0 0 1 * 1", "either"),
|
||||
("0 0 */2 * 1", "weekday"),
|
||||
("0 0 * 1 1", "weekday"),
|
||||
("0,1,5 * * * *", "48"),
|
||||
],
|
||||
)
|
||||
def test_a_shape_task_scheduler_cannot_take_is_refused(self, schedule, why):
|
||||
with pytest.raises(ScheduledJobRefused, match=why):
|
||||
task_xml.task_xml(_spec(schedule=schedule))
|
||||
|
||||
def test_an_expression_cron_would_not_take_is_refused(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="range"):
|
||||
task_xml.triggers("61 * * * *")
|
||||
|
||||
def test_at_most_48_triggers(self):
|
||||
assert len(_triggers("0,30 0-23 * * *")) == 1 # one repetition
|
||||
assert len(_triggers("0,20 0-11,13-23 * * *")) == 46
|
||||
with pytest.raises(ScheduledJobRefused, match="48"):
|
||||
task_xml.task_xml(_spec(schedule="0,20,30 0-11,13-23 * * *"))
|
||||
|
||||
|
||||
class TestTask:
|
||||
def test_the_description_names_the_job_and_keeps_its_cron_line(self):
|
||||
assert _text(_task(), "t:RegistrationInfo/t:Description") == (
|
||||
"napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *"
|
||||
)
|
||||
|
||||
def test_a_job_without_a_description(self):
|
||||
assert task_xml.description(_spec(description="")) == (
|
||||
"napalm-scheduled-job: nightly-dump\nschedule: 30 2 * * *"
|
||||
)
|
||||
|
||||
def test_the_command_runs_in_cmd(self):
|
||||
task = _task(command='"C:\\Program Files\\app.exe" -x & echo <done>')
|
||||
|
||||
assert _text(task, "t:Actions/t:Exec/t:Command") == "%SystemRoot%\\System32\\cmd.exe"
|
||||
assert _text(task, "t:Actions/t:Exec/t:Arguments") == (
|
||||
'/d /s /c ""C:\\Program Files\\app.exe" -x & echo <done>"'
|
||||
)
|
||||
|
||||
def test_the_xml_is_escaped(self):
|
||||
raw = task_xml.task_xml(_spec(command="a & b < c", description="x > y & z"))
|
||||
|
||||
assert "a & b < c" in raw
|
||||
assert "x > y & z" in raw
|
||||
|
||||
def test_a_user_runs_without_a_stored_password(self):
|
||||
task = _task(run_as="backup")
|
||||
|
||||
assert _text(task, "t:Principals/t:Principal/t:UserId") == "backup"
|
||||
assert _text(task, "t:Principals/t:Principal/t:LogonType") == "S4U"
|
||||
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "LeastPrivilege"
|
||||
|
||||
@pytest.mark.parametrize("run_as", ["SYSTEM", "system"])
|
||||
def test_system_is_the_local_system_account(self, run_as):
|
||||
task = _task(run_as=run_as)
|
||||
|
||||
assert _text(task, "t:Principals/t:Principal/t:UserId") == "S-1-5-18"
|
||||
assert _text(task, "t:Principals/t:Principal/t:LogonType") is None
|
||||
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "HighestAvailable"
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
def test_enabled_is_the_tasks_flag(self, enabled):
|
||||
assert _text(_task(enabled=enabled), "t:Settings/t:Enabled") == str(enabled).lower()
|
||||
|
||||
def test_runs_like_cron_on_battery_and_without_catching_up(self):
|
||||
task = _task()
|
||||
|
||||
assert _text(task, "t:Settings/t:DisallowStartIfOnBatteries") == "false"
|
||||
assert _text(task, "t:Settings/t:StopIfGoingOnBatteries") == "false"
|
||||
assert _text(task, "t:Settings/t:StartWhenAvailable") == "false"
|
||||
assert _text(task, "t:Settings/t:MultipleInstancesPolicy") == "IgnoreNew"
|
||||
|
||||
def test_a_command_is_one_line(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="one line"):
|
||||
task_xml.task_xml(_spec(command="echo a\necho b"))
|
||||
|
||||
def test_a_control_character_is_refused(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="control"):
|
||||
task_xml.task_xml(_spec(command="echo \x07"))
|
||||
|
||||
def test_trailing_whitespace_of_the_command_is_dropped(self):
|
||||
assert task_xml.command_action("echo hi\n") == (
|
||||
"%SystemRoot%\\System32\\cmd.exe",
|
||||
'/d /s /c "echo hi"',
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("execute", "arguments", "command"),
|
||||
[
|
||||
("%SystemRoot%\\System32\\cmd.exe", '/d /s /c "echo hi"', "echo hi"),
|
||||
("%systemroot%\\system32\\CMD.EXE", '/d /s /c "echo hi"', "echo hi"),
|
||||
("%SystemRoot%\\System32\\cmd.exe", "/c echo hi", None),
|
||||
("powershell.exe", '/d /s /c "echo hi"', None),
|
||||
("%SystemRoot%\\System32\\cmd.exe", None, None),
|
||||
],
|
||||
)
|
||||
def test_the_command_back_from_the_action(self, execute, arguments, command):
|
||||
assert task_xml.own_command(execute, arguments) == command
|
||||
@@ -0,0 +1,289 @@
|
||||
"""Time sync on Windows: w32time and the time zone over PowerShell Remoting (NetOrk/netork#2367).
|
||||
|
||||
The reading is one script whose JSON a fake host answers, starting from
|
||||
tests/fixtures/synthetic/time_sync.json (a workgroup host as Windows installs it:
|
||||
``time.windows.com,0x9``, Type NTP). The fake host applies what the write scripts
|
||||
say, so ``verify`` reads back what a host would. The status text is
|
||||
``w32tm /query /status`` as Windows prints it, in English and in German.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import TimeSyncMixin
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import time_sync as mod
|
||||
from napalm_windows.time_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA, windows_time_zone
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "time_sync.json"
|
||||
|
||||
UNSYNCED = (
|
||||
"Leap Indicator: 3(not synchronized)\nStratum: 0 (unspecified)\n"
|
||||
"Precision: -23 (119.209ns per tick)\nSource: Local CMOS Clock\n"
|
||||
)
|
||||
GERMAN = "Sprungindikator: 0(keine Warnung)\nStratum: 3 (Sekundärreferenz - synchr. über (S)NTP)\n"
|
||||
NOT_STARTED = "Folgender Fehler ist aufgetreten: Der Dienst wurde nicht gestartet. (0x80070426)\n"
|
||||
|
||||
|
||||
class FakeHost:
|
||||
"""Answers the reading from *state*; applies the write scripts to it."""
|
||||
|
||||
def __init__(self, **changes: Any) -> None:
|
||||
self.state: dict[str, Any] = {**json.loads(FIXTURE.read_text()), **changes}
|
||||
self.sent: list[str] = []
|
||||
self.fail: str | None = None
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
if script == mod._PS_TIME_SYNC:
|
||||
return json.dumps(self.state)
|
||||
if self.fail:
|
||||
raise PowerShellError(self.fail)
|
||||
peers = re.search(r"-Name NtpServer -Value '([^']*)'", script)
|
||||
if peers and "-Name Type -Value 'NTP'" in script and "w32tm /config /update" in script:
|
||||
self.state.update(type="NTP", ntp_server=peers.group(1), service="Running")
|
||||
zone = re.search(r"Set-TimeZone -Id '([^']*)'", script)
|
||||
if zone:
|
||||
self.state.update(zone=zone.group(1), dst_off="0")
|
||||
marker = re.search(r"-Name IanaTimeZone -Value '([^']*)'", script)
|
||||
if marker:
|
||||
self.state["iana_zone"] = marker.group(1)
|
||||
return ""
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
@property
|
||||
def writes(self) -> list[str]:
|
||||
return [s for s in self.sent if s != mod._PS_TIME_SYNC]
|
||||
|
||||
|
||||
def _driver(**changes: Any) -> tuple[WindowsDriver, FakeHost]:
|
||||
host = FakeHost(**changes)
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = host # type: ignore[assignment]
|
||||
return d, host
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The zone table (CLDR windowsZones.xml, generated)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestZoneTable:
|
||||
def test_every_windows_zone_reads_back_as_itself(self):
|
||||
"""The name a zone is read as is a name that writes that zone."""
|
||||
for windows, iana in WINDOWS_TO_IANA.items():
|
||||
assert IANA_TO_WINDOWS[iana] == windows
|
||||
|
||||
def test_every_name_is_a_real_zone(self):
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
for name in [*WINDOWS_TO_IANA.values(), *IANA_TO_WINDOWS]:
|
||||
ZoneInfo(name)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("iana", "windows"),
|
||||
[
|
||||
("Europe/Berlin", "W. Europe Standard Time"),
|
||||
("Europe/Vienna", "W. Europe Standard Time"),
|
||||
("Europe/London", "GMT Standard Time"),
|
||||
("Asia/Kolkata", "India Standard Time"), # CLDR keeps Asia/Calcutta
|
||||
("Asia/Calcutta", "India Standard Time"),
|
||||
("Europe/Kyiv", "FLE Standard Time"),
|
||||
("America/New_York", "Eastern Standard Time"),
|
||||
("Etc/UTC", "UTC"),
|
||||
("UTC", "UTC"), # a tzdata link to Etc/UTC
|
||||
("CET", None), # not a zone CLDR maps
|
||||
],
|
||||
)
|
||||
def test_an_iana_name_as_windows_zone(self, iana, windows):
|
||||
assert windows_time_zone(iana) == windows
|
||||
|
||||
def test_renamed_zones_read_as_their_current_name(self):
|
||||
assert WINDOWS_TO_IANA["India Standard Time"] == "Asia/Kolkata"
|
||||
assert WINDOWS_TO_IANA["FLE Standard Time"] == "Europe/Kyiv"
|
||||
assert WINDOWS_TO_IANA["Greenland Standard Time"] == "America/Nuuk"
|
||||
# A merge in tzdata is no rename: Reykjavik keeps its name.
|
||||
assert WINDOWS_TO_IANA["Greenwich Standard Time"] == "Atlantic/Reykjavik"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRead:
|
||||
def test_is_offered_and_writes_both(self):
|
||||
assert issubclass(WindowsDriver, TimeSyncMixin)
|
||||
assert callable(WindowsDriver.get_time_sync)
|
||||
assert WindowsDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
def test_a_workgroup_host_as_installed(self):
|
||||
d, host = _driver()
|
||||
assert d.get_time_sync() == {
|
||||
"ntp_servers": ["time.windows.com"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "w32time",
|
||||
}
|
||||
assert host.sent == [mod._PS_TIME_SYNC]
|
||||
|
||||
def test_servers_without_their_flags_in_order(self):
|
||||
d, _ = _driver(ntp_server="ntp1.example.org,0x8 10.0.0.1,0x8 ntp1.example.org,0x1")
|
||||
assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
|
||||
|
||||
def test_a_domain_member_reports_the_servers_configured(self):
|
||||
d, _ = _driver(type="NT5DS")
|
||||
assert d.get_time_sync()["ntp_servers"] == ["time.windows.com"]
|
||||
assert d.get_time_sync()["daemon"] == "w32time"
|
||||
|
||||
def test_group_policy_overrides_the_local_settings(self):
|
||||
d, _ = _driver(policy_type="NTP", policy_server="ntp.corp.example,0x8")
|
||||
assert d.get_time_sync()["ntp_servers"] == ["ntp.corp.example"]
|
||||
|
||||
def test_nosync_has_no_source(self):
|
||||
d, _ = _driver(type="NoSync")
|
||||
assert d.get_time_sync()["ntp_servers"] == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service", "status", "synchronized"),
|
||||
[
|
||||
("Running", UNSYNCED, False),
|
||||
("Running", GERMAN, True),
|
||||
("Running", NOT_STARTED, None),
|
||||
("Running", None, None),
|
||||
("Stopped", None, False),
|
||||
(None, None, None),
|
||||
],
|
||||
)
|
||||
def test_synchronized_from_the_leap_indicator(self, service, status, synchronized):
|
||||
d, _ = _driver(service=service, status=status)
|
||||
assert d.get_time_sync()["synchronized"] is synchronized
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("zone", "marker", "iana"),
|
||||
[
|
||||
("W. Europe Standard Time", "Europe/Vienna", "Europe/Vienna"),
|
||||
("GMT Standard Time", "Europe/Vienna", "Europe/London"), # changed by hand since
|
||||
("W. Europe Standard Time\u0000\u0000", None, "Europe/Berlin"),
|
||||
("Some Custom Standard Time", None, None),
|
||||
("", None, None),
|
||||
],
|
||||
)
|
||||
def test_the_zone(self, zone, marker, iana):
|
||||
d, _ = _driver(zone=zone, iana_zone=marker)
|
||||
assert d.get_time_sync()["timezone"] == iana
|
||||
|
||||
def test_summer_time_switched_off_is_not_the_zone(self):
|
||||
d, _ = _driver(dst_off="1", iana_zone="Europe/Berlin")
|
||||
assert d.get_time_sync()["timezone"] is None
|
||||
|
||||
def test_a_cut_reading_raises(self):
|
||||
d, host = _driver()
|
||||
host.run = lambda script: "" # type: ignore[method-assign]
|
||||
with pytest.raises(ValueError):
|
||||
d.get_time_sync()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Writing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestWriteServers:
|
||||
def test_sets_manual_peers_in_client_mode(self):
|
||||
d, host = _driver()
|
||||
result = d.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"])
|
||||
assert result["success"], result["output"]
|
||||
(script,) = host.writes
|
||||
assert "-Name NtpServer -Value 'ntp1.example.org,0x8 10.0.0.1,0x8'" in script
|
||||
assert "-Name Type -Value 'NTP'" in script
|
||||
assert "Start-Service -Name W32Time" in script
|
||||
assert script.index("Set-ItemProperty") < script.index("w32tm /config /update")
|
||||
assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
|
||||
|
||||
def test_the_same_servers_again_write_nothing(self):
|
||||
d, host = _driver(ntp_server="NTP1.example.org,0x8")
|
||||
result = d.configure_time_sync(ntp_servers=["ntp1.example.org"])
|
||||
assert result["success"], result["output"]
|
||||
assert host.writes == []
|
||||
|
||||
def test_nosync_with_the_same_servers_is_written(self):
|
||||
d, host = _driver(type="NoSync", ntp_server="ntp1.example.org,0x8")
|
||||
assert d.configure_time_sync(ntp_servers=["ntp1.example.org"])["success"]
|
||||
assert len(host.writes) == 1
|
||||
|
||||
@pytest.mark.parametrize("kind", ["NT5DS", "AllSync"])
|
||||
def test_a_domain_member_is_refused(self, kind):
|
||||
d, host = _driver(type=kind)
|
||||
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
|
||||
assert not result["success"]
|
||||
assert "domain" in result["steps"][0]["output"]
|
||||
assert host.writes == []
|
||||
|
||||
def test_group_policy_is_refused(self):
|
||||
d, host = _driver(policy_server="ntp.corp.example,0x8")
|
||||
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
|
||||
assert not result["success"]
|
||||
assert "group policy" in result["steps"][0]["output"]
|
||||
assert host.writes == []
|
||||
|
||||
def test_a_failed_script_fails_the_step(self):
|
||||
d, host = _driver()
|
||||
host.fail = "w32tm /config: The service cannot be started (0x80070422)"
|
||||
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
|
||||
assert not result["success"]
|
||||
assert "0x80070422" in result["steps"][0]["output"]
|
||||
|
||||
|
||||
class TestWriteZone:
|
||||
def test_sets_the_windows_zone_and_remembers_the_name(self):
|
||||
d, host = _driver(zone="GMT Standard Time")
|
||||
result = d.configure_time_sync(timezone="Europe/Vienna")
|
||||
assert result["success"], result["output"]
|
||||
(script,) = host.writes
|
||||
assert "Set-TimeZone -Id 'W. Europe Standard Time'" in script
|
||||
assert "-Name IanaTimeZone -Value 'Europe/Vienna'" in script
|
||||
assert d.get_time_sync()["timezone"] == "Europe/Vienna"
|
||||
|
||||
def test_the_same_windows_zone_only_remembers_the_name(self):
|
||||
d, host = _driver()
|
||||
result = d.configure_time_sync(timezone="Europe/Vienna")
|
||||
assert result["success"], result["output"]
|
||||
(script,) = host.writes
|
||||
assert "Set-TimeZone" not in script
|
||||
assert d.get_time_sync()["timezone"] == "Europe/Vienna"
|
||||
|
||||
def test_the_same_zone_again_writes_nothing(self):
|
||||
d, host = _driver(iana_zone="Europe/Berlin")
|
||||
assert d.configure_time_sync(timezone="Europe/Berlin")["success"]
|
||||
assert host.writes == []
|
||||
|
||||
def test_summer_time_off_is_turned_on(self):
|
||||
d, host = _driver(dst_off="1", iana_zone="Europe/Berlin")
|
||||
result = d.configure_time_sync(timezone="Europe/Berlin")
|
||||
assert result["success"], result["output"]
|
||||
assert "Set-TimeZone -Id 'W. Europe Standard Time'" in host.writes[0]
|
||||
|
||||
def test_a_zone_windows_does_not_have_is_refused(self):
|
||||
d, host = _driver()
|
||||
result = d.configure_time_sync(timezone="CET")
|
||||
assert not result["success"]
|
||||
assert "no Windows time zone" in result["steps"][0]["output"]
|
||||
assert host.writes == []
|
||||
|
||||
def test_servers_and_zone_together(self):
|
||||
d, host = _driver()
|
||||
result = d.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="America/New_York")
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
assert d.get_time_sync()["timezone"] == "America/New_York"
|
||||
+47
-1
@@ -11,7 +11,7 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
|
||||
from pypsrp.exceptions import AuthenticationError, WinRMTransportError
|
||||
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
|
||||
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
|
||||
@@ -120,6 +120,52 @@ class TestRun:
|
||||
_transport().run("Get-Thing")
|
||||
|
||||
|
||||
class TestRunLast:
|
||||
"""A script that may take WinRM down with it: a restart, a shutdown."""
|
||||
|
||||
def test_a_finished_script_is_true(self, psrp):
|
||||
psrp["ps"].return_value.invoke.return_value = []
|
||||
psrp["ps"].return_value.had_errors = False
|
||||
t = _transport()
|
||||
t.open()
|
||||
|
||||
assert t.run_last("Restart-Computer") is True
|
||||
psrp["ps"].return_value.add_script.assert_called_once_with("Restart-Computer")
|
||||
assert t.is_open is True
|
||||
|
||||
def test_the_error_stream_still_raises_powershell_error(self, psrp):
|
||||
psrp["ps"].return_value.invoke.return_value = []
|
||||
psrp["ps"].return_value.had_errors = True
|
||||
psrp["ps"].return_value.streams.error = ["other users logged on"]
|
||||
t = _transport()
|
||||
t.open()
|
||||
|
||||
with pytest.raises(PowerShellError, match="other users logged on"):
|
||||
t.run_last("Restart-Computer")
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
requests.ConnectionError("connection reset by peer"),
|
||||
requests.ReadTimeout("read timed out"),
|
||||
WinRMTransportError("http", 503, "Service Unavailable"),
|
||||
WinRMError("the shell was terminated"),
|
||||
ConnectionResetError(104, "Connection reset by peer"),
|
||||
],
|
||||
)
|
||||
def test_a_connection_that_breaks_is_false_and_closed(self, psrp, error):
|
||||
psrp["ps"].return_value.invoke.side_effect = error
|
||||
t = _transport()
|
||||
t.open()
|
||||
|
||||
assert t.run_last("Restart-Computer") is False
|
||||
assert t.is_open is False
|
||||
|
||||
def test_run_last_before_open_raises_connection_closed(self):
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
_transport().run_last("Restart-Computer")
|
||||
|
||||
|
||||
class TestClose:
|
||||
def test_close_closes_pool_and_connection(self, psrp):
|
||||
t = _transport()
|
||||
|
||||
+76
-3
@@ -28,9 +28,15 @@ def _fixture(name: str) -> str:
|
||||
class FakeTransport:
|
||||
"""Answers the driver's scripts from fixtures and records what it was sent."""
|
||||
|
||||
def __init__(self, answers: dict[str, str] | None = None, error: str | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
answers: dict[str, str] | None = None,
|
||||
error: str | None = None,
|
||||
drops: bool = False,
|
||||
):
|
||||
self.answers = answers or {}
|
||||
self.error = error
|
||||
self.drops = drops
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
@@ -40,6 +46,14 @@ class FakeTransport:
|
||||
raise PowerShellError(self.error)
|
||||
return self.answers.get(script, "")
|
||||
|
||||
def run_last(self, script: str) -> bool:
|
||||
self.sent.append(script)
|
||||
if self.error:
|
||||
raise PowerShellError(self.error)
|
||||
if self.drops:
|
||||
self.is_open = False
|
||||
return not self.drops
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
@@ -297,10 +311,17 @@ class TestGetArpTable:
|
||||
arp = _driver(_PS_ARP=_fixture("arp.json")).get_arp_table()
|
||||
|
||||
assert arp == [
|
||||
{"interface": "Ethernet", "mac": "00:0D:B9:11:22:33", "ip": "10.0.0.1", "age": 0.0},
|
||||
{"interface": "Ethernet", "mac": "00:15:5D:AA:BB:CC", "ip": "10.0.0.20", "age": 0.0},
|
||||
{"interface": "Ethernet", "mac": "00:0D:B9:11:22:33", "ip": "10.0.0.1", "age": -1.0},
|
||||
{"interface": "Ethernet", "mac": "00:15:5D:AA:BB:CC", "ip": "10.0.0.20", "age": -1.0},
|
||||
]
|
||||
|
||||
def test_age_is_unknown(self):
|
||||
"""Get-NetNeighbor has a state but no age; 0.0 would read as "confirmed
|
||||
just now" to a caller ranking sightings by freshness (NetOrk/netork#1327)."""
|
||||
arp = _driver(_PS_ARP=_fixture("arp.json")).get_arp_table()
|
||||
|
||||
assert {entry["age"] for entry in arp} == {-1.0}
|
||||
|
||||
|
||||
class TestGetRouteTo:
|
||||
def test_maps_protocols_and_drops_noise(self):
|
||||
@@ -483,3 +504,55 @@ class TestManageService:
|
||||
"success": False,
|
||||
"output": "Cannot find any service with service name 'nope'.",
|
||||
}
|
||||
|
||||
|
||||
class TestHostPower:
|
||||
"""``reboot_host`` and ``shutdown_host``: the clean restart and shutdown of the host
|
||||
itself, never a forced one (NetOrk/netork#2841)."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "cmdlet"),
|
||||
[("reboot_host", "Restart-Computer"), ("shutdown_host", "Stop-Computer")],
|
||||
)
|
||||
def test_sends_the_cmdlet_without_force(self, method, cmdlet):
|
||||
d = _driver()
|
||||
|
||||
getattr(d, method)()
|
||||
|
||||
(script,) = d._transport.sent
|
||||
assert script.startswith(cmdlet)
|
||||
assert "-ErrorAction Stop" in script
|
||||
assert "-Force" not in script
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "what"), [("reboot_host", "restart"), ("shutdown_host", "shut down")]
|
||||
)
|
||||
def test_a_refusal_raises_with_the_hosts_answer(self, method, what):
|
||||
answer = (
|
||||
"Failed to restart the computer WIN01 with the following error message: The "
|
||||
"system shutdown cannot be initiated because there are other users logged on "
|
||||
"to the computer."
|
||||
)
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(error=answer)
|
||||
|
||||
with pytest.raises(RuntimeError, match=f"refused to {what}: Failed to restart"):
|
||||
getattr(d, method)()
|
||||
|
||||
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
|
||||
def test_a_connection_dropped_by_the_host_counts_as_accepted(self, method):
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(drops=True)
|
||||
|
||||
getattr(d, method)()
|
||||
|
||||
assert len(d._transport.sent) == 1
|
||||
|
||||
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
|
||||
def test_before_open_raises_connection_closed(self, method):
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
getattr(WindowsDriver("win01", "admin", "secret"), method)()
|
||||
|
||||
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
|
||||
def test_the_capability_is_there_for_introspection(self, method):
|
||||
assert callable(getattr(WindowsDriver("win01", "admin", "secret"), method, None))
|
||||
@@ -0,0 +1,62 @@
|
||||
"""tools/windows_zones.py: the generator of napalm_windows/_windows_zones.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
TOOL = Path(__file__).parent.parent / "tools" / "windows_zones.py"
|
||||
_spec = importlib.util.spec_from_file_location("windows_zones_tool", TOOL)
|
||||
assert _spec is not None and _spec.loader is not None
|
||||
tool = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(tool)
|
||||
|
||||
XML = """<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<supplementalData><windowsZones><mapTimezones>
|
||||
<mapZone other="India Standard Time" territory="001" type="Asia/Calcutta"/>
|
||||
<mapZone other="India Standard Time" territory="IN" type="Asia/Calcutta"/>
|
||||
<mapZone other="Greenwich Standard Time" territory="001" type="Atlantic/Reykjavik"/>
|
||||
<mapZone other="Greenwich Standard Time" territory="CI" type="Africa/Abidjan"/>
|
||||
<mapZone other="UTC" territory="001" type="Etc/UTC"/>
|
||||
<mapZone other="UTC" territory="ZZ" type="Etc/UTC Etc/GMT"/>
|
||||
</mapTimezones></windowsZones></supplementalData>
|
||||
"""
|
||||
|
||||
TZDATA = """# version 2026e
|
||||
Z Etc/UTC 0 - UTC
|
||||
L Asia/Kolkata Asia/Calcutta
|
||||
L Africa/Abidjan Atlantic/Reykjavik
|
||||
L Etc/UTC UTC
|
||||
"""
|
||||
|
||||
|
||||
def _tables(tmp_path: Path) -> tuple[dict[str, str], dict[str, str]]:
|
||||
(tmp_path / "w.xml").write_text(XML)
|
||||
(tmp_path / "tzdata.zi").write_text(TZDATA)
|
||||
primary, to_windows, _ = tool.read_cldr(tmp_path / "w.xml")
|
||||
return tool.build(primary, to_windows, tool.read_links(tmp_path / "tzdata.zi"))
|
||||
|
||||
|
||||
def test_a_renamed_zone_reads_as_its_new_name(tmp_path):
|
||||
windows_to_iana, iana_to_windows = _tables(tmp_path)
|
||||
assert windows_to_iana["India Standard Time"] == "Asia/Kolkata"
|
||||
assert iana_to_windows["Asia/Kolkata"] == iana_to_windows["Asia/Calcutta"]
|
||||
|
||||
|
||||
def test_a_merged_zone_keeps_its_name(tmp_path):
|
||||
windows_to_iana, _ = _tables(tmp_path)
|
||||
assert windows_to_iana["Greenwich Standard Time"] == "Atlantic/Reykjavik"
|
||||
|
||||
|
||||
def test_links_to_a_mapped_zone_are_mapped(tmp_path):
|
||||
_, iana_to_windows = _tables(tmp_path)
|
||||
assert iana_to_windows["UTC"] == "UTC"
|
||||
assert iana_to_windows["Etc/GMT"] == "UTC"
|
||||
|
||||
|
||||
def test_the_module_names_its_sources(tmp_path):
|
||||
text = tool.render(*_tables(tmp_path), "release-49", "abc", "2026e")
|
||||
assert "CLDR release-49" in text and "sha256 abc" in text and "2026e" in text
|
||||
namespace: dict[str, object] = {}
|
||||
exec(compile(text, "generated", "exec"), namespace)
|
||||
assert namespace["WINDOWS_TO_IANA"] == _tables(tmp_path)[0]
|
||||
+6
-1
@@ -14,7 +14,7 @@ import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import WindowsDriver, scheduled_tasks, storage, time_sync
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
SCRIPTS = {
|
||||
@@ -25,6 +25,11 @@ SCRIPTS = {
|
||||
"routes": mod._PS_ROUTES,
|
||||
"services": mod._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,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Generate napalm_windows/_windows_zones.py from CLDR's windowsZones.xml and tzdata's links.
|
||||
|
||||
python tools/windows_zones.py windowsZones.xml /usr/share/zoneinfo/tzdata.zi \\
|
||||
--cldr release-49 > napalm_windows/_windows_zones.py
|
||||
|
||||
windowsZones.xml is CLDR's mapping of Windows zone ids to IANA names
|
||||
(https://github.com/unicode-org/cldr/blob/<release>/common/supplemental/windowsZones.xml);
|
||||
tzdata.zi is the compact form of the IANA database, read for its link lines (``L target
|
||||
alias``). The driver never fetches either at runtime: rerun this when a new CLDR release
|
||||
adds Windows zones, and commit the result.
|
||||
|
||||
* ``WINDOWS_TO_IANA``: each Windows zone's territory ``001`` zone -- the one name CLDR
|
||||
gives it. CLDR keeps old names (``Asia/Calcutta``, ``Europe/Kiev``); one that is a
|
||||
link in tzdata to a zone CLDR does not name is replaced by that zone (``Asia/Kolkata``).
|
||||
A link to a zone CLDR does name is a merge, not a rename (``Atlantic/Reykjavik`` ->
|
||||
``Africa/Abidjan``), and keeps its own name.
|
||||
* ``IANA_TO_WINDOWS``: every IANA name CLDR maps, in any territory, to its Windows zone;
|
||||
plus each tzdata link to or from such a name that CLDR does not map itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import pathlib
|
||||
import xml.etree.ElementTree as ET # nosec B405 - a file the developer downloaded, not input
|
||||
|
||||
|
||||
def read_cldr(path: pathlib.Path) -> tuple[dict[str, str], dict[str, str], set[str]]:
|
||||
"""``(windows -> 001 zone, every CLDR zone -> windows, all CLDR names)``."""
|
||||
primary: dict[str, str] = {}
|
||||
to_windows: dict[str, str] = {}
|
||||
for node in ET.parse(path).iter("mapZone"): # nosec B314
|
||||
windows, names = node.attrib["other"], node.attrib["type"].split()
|
||||
if node.attrib["territory"] == "001":
|
||||
primary[windows] = names[0]
|
||||
for name in names:
|
||||
if to_windows.setdefault(name, windows) != windows:
|
||||
raise SystemExit(f"{name} maps to {to_windows[name]} and {windows}")
|
||||
return primary, to_windows, set(to_windows)
|
||||
|
||||
|
||||
def read_links(path: pathlib.Path) -> list[tuple[str, str]]:
|
||||
"""tzdata's ``(target, alias)`` links."""
|
||||
links = []
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith("L "):
|
||||
_, target, alias = line.split()
|
||||
links.append((target, alias))
|
||||
return links
|
||||
|
||||
|
||||
def build(
|
||||
primary: dict[str, str], to_windows: dict[str, str], links: list[tuple[str, str]]
|
||||
) -> tuple[dict[str, str], dict[str, str]]:
|
||||
cldr = set(to_windows)
|
||||
renamed = {alias: target for target, alias in links if target not in cldr}
|
||||
windows_to_iana = {w: renamed.get(name, name) for w, name in sorted(primary.items())}
|
||||
iana_to_windows = dict(to_windows)
|
||||
for target, alias in links:
|
||||
if target in to_windows and alias not in iana_to_windows:
|
||||
iana_to_windows[alias] = to_windows[target]
|
||||
elif alias in to_windows and target not in iana_to_windows:
|
||||
iana_to_windows[target] = to_windows[alias]
|
||||
return windows_to_iana, dict(sorted(iana_to_windows.items()))
|
||||
|
||||
|
||||
def render(
|
||||
windows_to_iana: dict[str, str],
|
||||
iana_to_windows: dict[str, str],
|
||||
cldr_release: str,
|
||||
cldr_sha: str,
|
||||
tz_version: str,
|
||||
) -> str:
|
||||
lines = [
|
||||
'"""Windows time zones and IANA names. Generated by tools/windows_zones.py: do not edit.',
|
||||
"",
|
||||
f"Source: CLDR {cldr_release}, common/supplemental/windowsZones.xml",
|
||||
f"(sha256 {cldr_sha}),",
|
||||
f"with the link lines of the IANA time zone database {tz_version} (tzdata.zi).",
|
||||
'"""',
|
||||
"",
|
||||
"WINDOWS_TO_IANA: dict[str, str] = {",
|
||||
*(f' "{w}": "{name}",' for w, name in windows_to_iana.items()),
|
||||
"}",
|
||||
"",
|
||||
"IANA_TO_WINDOWS: dict[str, str] = {",
|
||||
*(f' "{name}": "{w}",' for name, w in iana_to_windows.items()),
|
||||
"}",
|
||||
"",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("windows_zones", type=pathlib.Path)
|
||||
ap.add_argument("tzdata_zi", type=pathlib.Path)
|
||||
ap.add_argument("--cldr", required=True, help="the CLDR release the XML is from")
|
||||
args = ap.parse_args()
|
||||
primary, to_windows, _ = read_cldr(args.windows_zones)
|
||||
links = read_links(args.tzdata_zi)
|
||||
tz_version = args.tzdata_zi.read_text().splitlines()[0].removeprefix("# version ").strip()
|
||||
sha = hashlib.sha256(args.windows_zones.read_bytes()).hexdigest()
|
||||
print(render(*build(primary, to_windows, links), args.cldr, sha, tz_version), end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user