Files
napalm-windows/tools/windows_zones.py
T
Christian Manivong 0b30ab00a5
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 58s
driver / test (3.13) (pull_request) Successful in 51s
driver / lowest (pull_request) Successful in 26s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Successful in 2m23s
driver / publish (pull_request) Skipped
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
2026-11-11 15:27:56 +01:00

110 lines
4.5 KiB
Python

"""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()