From 0b30ab00a5bd4be2ccdc6e12c479fe93a82e6f45 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 11 Nov 2026 15:27:56 +0100 Subject: [PATCH] feat(time-sync): w32time's servers and the time zone through TimeSyncMixin netOrk keeps one list of NTP servers and a time zone per site and aligns a device that differs (NetOrk/netork#2360). A Windows host takes part through w32time and its time zone, in one PowerShell script per read. The servers and the mode are read from w32time's registry values, group policy's first, not from w32tm /query /configuration, whose text is in the host's language; synchronised is the leap indicator on the first line of w32tm /query /status, which reads the same in any language. The servers are written the way w32tm /config /manualpeerlist /syncfromflags:manual writes them (NtpServer with 0x8, Type NTP), followed by w32tm /config /update: no value passes a native command line, whose quoting Windows PowerShell 5.1 mangles. A domain member that takes its time from the domain hierarchy (NT5DS, AllSync) and a host whose w32time comes from group policy refuse the write: their time is set elsewhere, and a local write would be overridden or break the domain's time. Windows keeps a Windows zone, which stands for several IANA zones, so Europe/Vienna written would read back as Europe/Berlin and the poll would align the host forever. The IANA name written is kept beside it in HKLM\SOFTWARE\napalm-windows and read back while the host is still in that Windows zone. The zone is read from the registry, which [TimeZoneInfo]::Local caches for the life of the remote session. The zone table is now CLDR's windowsZones.xml (release 49) both ways, generated by tools/windows_zones.py with tzdata's links and committed with its source and checksum; nothing is fetched at runtime. CLDR's old names (Asia/Calcutta) read as their current ones (Asia/Kolkata). Writes the host already has are skipped. Needs napalm-device-types 4.35.0. Refs NetOrk/netork#2367 --- CHANGELOG.md | 17 +- README.md | 26 + napalm_windows/_windows_zones.py | 732 ++++++++++++++++++++++++ napalm_windows/time_sync.py | 221 +++++++ napalm_windows/time_zones.py | 124 +--- napalm_windows/windows.py | 3 +- pyproject.toml | 2 +- tests/fixtures/synthetic/time_sync.json | 1 + tests/test_time_sync.py | 289 ++++++++++ tests/test_windows_zones_tool.py | 62 ++ tools/harvest.py | 3 +- tools/windows_zones.py | 109 ++++ 12 files changed, 1481 insertions(+), 108 deletions(-) create mode 100644 napalm_windows/_windows_zones.py create mode 100644 napalm_windows/time_sync.py create mode 100644 tests/fixtures/synthetic/time_sync.json create mode 100644 tests/test_time_sync.py create mode 100644 tests/test_windows_zones_tool.py create mode 100644 tools/windows_zones.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c371e0..5c28932 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Added +- 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 `,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:`: a task under @@ -22,7 +37,7 @@ All notable changes to this driver. The format follows the task again first and refuses over a change it did not see. Fixture synthetic. ### Changed -- The floor on napalm-device-types is 4.26.0, which declares the scheduled-jobs contract. +- 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 diff --git a/README.md b/README.md index c5c72ad..4b20b10 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ handshake once. | `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* | `running_kernel` carries the full build including the update revision (`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE @@ -70,6 +71,31 @@ changed by hand count as a change. 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 `,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. + Not yet: packages, Windows Update, health metrics, Hyper-V. See netork#300 for the plan. diff --git a/napalm_windows/_windows_zones.py b/napalm_windows/_windows_zones.py new file mode 100644 index 0000000..8ef5e77 --- /dev/null +++ b/napalm_windows/_windows_zones.py @@ -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", +} diff --git a/napalm_windows/time_sync.py b/napalm_windows/time_sync.py new file mode 100644 index 0000000..1eef1d6 --- /dev/null +++ b/napalm_windows/time_sync.py @@ -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})"} diff --git a/napalm_windows/time_zones.py b/napalm_windows/time_zones.py index 4834279..efe5bcb 100644 --- a/napalm_windows/time_zones.py +++ b/napalm_windows/time_zones.py @@ -1,115 +1,31 @@ -"""Windows time zone ids as IANA names, for the scheduled-jobs reading (#8). +"""Windows time zone ids and IANA names, both ways. Windows names its zones by their standard-time name (``W. Europe Standard Time``); -the contract wants an IANA name. The table holds the common zones, each mapped to -the zone CLDR names for its territory ``001`` (``windowsZones.xml``); a zone not in -it is ``None`` -- the reading says it does not know rather than guess. +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 -WINDOWS_TO_IANA: dict[str, str] = { - # UTC and fixed offsets - "UTC": "Etc/UTC", - "Dateline Standard Time": "Etc/GMT+12", - "UTC-11": "Etc/GMT+11", - "UTC-09": "Etc/GMT+9", - "UTC-08": "Etc/GMT+8", - "UTC-02": "Etc/GMT+2", - "UTC+12": "Etc/GMT-12", - "UTC+13": "Etc/GMT-13", - # Europe - "GMT Standard Time": "Europe/London", - "Greenwich Standard Time": "Atlantic/Reykjavik", - "W. Europe Standard Time": "Europe/Berlin", - "Central Europe Standard Time": "Europe/Budapest", - "Romance Standard Time": "Europe/Paris", - "Central European Standard Time": "Europe/Warsaw", - "GTB Standard Time": "Europe/Bucharest", - "E. Europe Standard Time": "Europe/Chisinau", - "FLE Standard Time": "Europe/Kyiv", - "Turkey Standard Time": "Europe/Istanbul", - "Kaliningrad Standard Time": "Europe/Kaliningrad", - "Russian Standard Time": "Europe/Moscow", - "Belarus Standard Time": "Europe/Minsk", - "Azores Standard Time": "Atlantic/Azores", - "Cape Verde Standard Time": "Atlantic/Cape_Verde", - # Africa and the Middle East - "Morocco Standard Time": "Africa/Casablanca", - "W. Central Africa Standard Time": "Africa/Lagos", - "Egypt Standard Time": "Africa/Cairo", - "South Africa Standard Time": "Africa/Johannesburg", - "E. Africa Standard Time": "Africa/Nairobi", - "Namibia Standard Time": "Africa/Windhoek", - "Israel Standard Time": "Asia/Jerusalem", - "Jordan Standard Time": "Asia/Amman", - "Middle East Standard Time": "Asia/Beirut", - "Arabic Standard Time": "Asia/Baghdad", - "Arab Standard Time": "Asia/Riyadh", - "Iran Standard Time": "Asia/Tehran", - "Arabian Standard Time": "Asia/Dubai", - # Asia and the Pacific - "Georgian Standard Time": "Asia/Tbilisi", - "Azerbaijan Standard Time": "Asia/Baku", - "Caucasus Standard Time": "Asia/Yerevan", - "Afghanistan Standard Time": "Asia/Kabul", - "Pakistan Standard Time": "Asia/Karachi", - "West Asia Standard Time": "Asia/Tashkent", - "Ekaterinburg Standard Time": "Asia/Yekaterinburg", - "India Standard Time": "Asia/Kolkata", - "Sri Lanka Standard Time": "Asia/Colombo", - "Nepal Standard Time": "Asia/Kathmandu", - "Bangladesh Standard Time": "Asia/Dhaka", - "Myanmar Standard Time": "Asia/Yangon", - "SE Asia Standard Time": "Asia/Bangkok", - "N. Central Asia Standard Time": "Asia/Novosibirsk", - "North Asia Standard Time": "Asia/Krasnoyarsk", - "China Standard Time": "Asia/Shanghai", - "Singapore Standard Time": "Asia/Singapore", - "Taipei Standard Time": "Asia/Taipei", - "W. Australia Standard Time": "Australia/Perth", - "Tokyo Standard Time": "Asia/Tokyo", - "Korea Standard Time": "Asia/Seoul", - "Cen. Australia Standard Time": "Australia/Adelaide", - "AUS Central Standard Time": "Australia/Darwin", - "E. Australia Standard Time": "Australia/Brisbane", - "AUS Eastern Standard Time": "Australia/Sydney", - "Tasmania Standard Time": "Australia/Hobart", - "Vladivostok Standard Time": "Asia/Vladivostok", - "New Zealand Standard Time": "Pacific/Auckland", - "Fiji Standard Time": "Pacific/Fiji", - "Tonga Standard Time": "Pacific/Tongatapu", - "Samoa Standard Time": "Pacific/Apia", - # The Americas - "Hawaiian Standard Time": "Pacific/Honolulu", - "Aleutian Standard Time": "America/Adak", - "Alaskan Standard Time": "America/Anchorage", - "Pacific Standard Time": "America/Los_Angeles", - "Pacific Standard Time (Mexico)": "America/Tijuana", - "US Mountain Standard Time": "America/Phoenix", - "Mountain Standard Time": "America/Denver", - "Central America Standard Time": "America/Guatemala", - "Central Standard Time": "America/Chicago", - "Central Standard Time (Mexico)": "America/Mexico_City", - "Canada Central Standard Time": "America/Regina", - "SA Pacific Standard Time": "America/Bogota", - "Eastern Standard Time": "America/New_York", - "US Eastern Standard Time": "America/Indiana/Indianapolis", - "Cuba Standard Time": "America/Havana", - "Venezuela Standard Time": "America/Caracas", - "Atlantic Standard Time": "America/Halifax", - "SA Western Standard Time": "America/La_Paz", - "Pacific SA Standard Time": "America/Santiago", - "Paraguay Standard Time": "America/Asuncion", - "Newfoundland Standard Time": "America/St_Johns", - "E. South America Standard Time": "America/Sao_Paulo", - "Argentina Standard Time": "America/Argentina/Buenos_Aires", - "SA Eastern Standard Time": "America/Cayenne", - "Montevideo Standard Time": "America/Montevideo", - "Greenland Standard Time": "America/Nuuk", -} +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"] diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index 6e09783..1cd0136 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -28,6 +28,7 @@ from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict from napalm_windows._powershell import _as_list, _ps_quote from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin +from napalm_windows.time_sync import WindowsTimeSyncMixin from napalm_windows.transport import PowerShellError, PsrpTransport logger = logging.getLogger(__name__) @@ -254,7 +255,7 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(WindowsScheduledJobsMixin, OSDriver): +class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: diff --git a/pyproject.toml b/pyproject.toml index 7224cd3..343db3d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.27.0", # ScheduledJobsMixin + "napalm-device-types>=4.35.0", # TimeSyncMixin "pypsrp>=0.8", ] diff --git a/tests/fixtures/synthetic/time_sync.json b/tests/fixtures/synthetic/time_sync.json new file mode 100644 index 0000000..9493740 --- /dev/null +++ b/tests/fixtures/synthetic/time_sync.json @@ -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} diff --git a/tests/test_time_sync.py b/tests/test_time_sync.py new file mode 100644 index 0000000..310f139 --- /dev/null +++ b/tests/test_time_sync.py @@ -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" diff --git a/tests/test_windows_zones_tool.py b/tests/test_windows_zones_tool.py new file mode 100644 index 0000000..ae6cea5 --- /dev/null +++ b/tests/test_windows_zones_tool.py @@ -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 = """ + + + + + + + + +""" + +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] diff --git a/tools/harvest.py b/tools/harvest.py index 194c9d3..38de2f4 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -14,7 +14,7 @@ import argparse import getpass import pathlib -from napalm_windows import WindowsDriver, scheduled_tasks +from napalm_windows import WindowsDriver, scheduled_tasks, time_sync from napalm_windows import windows as mod SCRIPTS = { @@ -26,6 +26,7 @@ SCRIPTS = { "services": mod._PS_SERVICES, "listening": mod._PS_LISTENING, "scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS, + "time_sync": time_sync._PS_TIME_SYNC, } OUT = pathlib.Path(__file__).parent / "harvest-out" diff --git a/tools/windows_zones.py b/tools/windows_zones.py new file mode 100644 index 0000000..f6c8d38 --- /dev/null +++ b/tools/windows_zones.py @@ -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//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()