okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1d0397652
main
1"""serve/telemetry.py `_cpu_topology`: how many CPU sockets and NUMA nodes the computer has (for "2 CPUs · 64 cores" in the monitor).""" 2 3from __future__import annotations 4 5import os 6import sys 7import tempfile 8import unittest 9from pathlib import Path 10from unittest import mock 11 12from serve import telemetry 13 14 15def fake_sysfs (root :Path ,packages :list [int ],nodes :int )-> None : 16for i ,pkg in enumerate (packages ): 17d = root / "cpu" / f"cpu { i } " / "topology" 18d .mkdir (parents = True ) 19 (d / "physical_package_id" ).write_text (f" { pkg } \n" ) 20 (root / "cpu" / "cpufreq" ).mkdir ()# not a cpuN folder: never counted 21for n in range (nodes ): 22 (root / "node" / f"node { n } " ).mkdir (parents = True ) 23 24 25class Topology (unittest .TestCase ): 26def read (self ,root ): 27with mock .patch .object (telemetry .os ,"name" ,"posix" ),mock .patch .object (telemetry .sys ,"platform" ,"linux" ): 28return telemetry ._cpu_topology (str (root )) 29 30def test_two_sockets_two_numa_nodes (self ): 31with tempfile .TemporaryDirectory ()as tmp : 32fake_sysfs (Path (tmp ), [0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ],2 )# 8 logical CPUs on 2 packages 33self .assertEqual (self .read (tmp ), (2 ,2 )) 34 35def test_one_socket (self ): 36with tempfile .TemporaryDirectory ()as tmp : 37fake_sysfs (Path (tmp ), [0 ,0 ,0 ,0 ],1 ) 38self .assertEqual (self .read (tmp ), (1 ,1 )) 39 40def test_one_socket_with_several_memory_nodes (self ):# e.g. an EPYC with NPS4: one package, four nodes 41with tempfile .TemporaryDirectory ()as tmp : 42fake_sysfs (Path (tmp ), [0 ]* 8 ,4 ) 43self .assertEqual (self .read (tmp ), (1 ,4 )) 44 45def test_nothing_readable_is_none_not_a_guess (self ): 46with tempfile .TemporaryDirectory ()as tmp : 47self .assertEqual (self .read (tmp ), (None ,None )) 48 49def test_this_computer_answers_in_numbers (self ): 50sockets ,numa = telemetry ._cpu_topology () 51self .assertTrue (sockets is None or sockets >= 1 ) 52self .assertTrue (numa is None or numa >= 1 ) 53 54def test_the_hardware_info_carries_them (self ): 55src = (Path (telemetry .__file__ )).read_text (encoding = "utf-8" ) 56self .assertIn ('"sockets"' ,src ) 57self .assertIn ('"numa_nodes"' ,src ) 58 59 60if __name__ == "__main__" : 61unittest .main ()