okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5a6ef1d76
main
1"""Split a launcher's allowed physical cores between independent Linux instances.""" 2from __future__import annotations 3 4import argparse 5import os 6from pathlib import Path 7import sys 8 9 10def partition_cpu_sets (count :int ,allowed :set [int ],reserved :set [int ]| None = None , 11sys_root :Path = Path ("/sys" ))-> list [list [int ]]: 12if count < 1 : 13raise ValueError ("the instance count must be positive" ) 14if not allowed : 15raise ValueError ("no CPUs are allowed for this launcher" ) 16if count == 1 and not reserved : 17return [sorted (allowed )] 18cores :dict [tuple [int ,int ],list [int ]]= {} 19occupied :set [tuple [int ,int ]]= set () 20for cpu in sorted (allowed | (reserved or set ())): 21topology = sys_root / "devices/system/cpu" / f"cpu { cpu } " / "topology" 22try : 23key = (int ((topology / "physical_package_id" ).read_text ()), 24int ((topology / "core_id" ).read_text ())) 25except (OSError ,ValueError )as error : 26raise ValueError (f"cannot read physical-core topology for CPU { cpu } : { error } " )from error 27if cpu in allowed : 28cores .setdefault (key , []).append (cpu ) 29if reserved and cpu in reserved : 30occupied .add (key ) 31available = sorted ((cpus for key ,cpus in cores .items ()if key not in occupied ),key = min ) 32if len (available )< count : 33raise ValueError ( 34f" { count } instances need at least { count } free physical cores, but only { len ( available ) } " 35"are available; restart the managed instances together or expand the launcher's CPU set" 36 ) 37size ,extra = divmod (len (available ),count ) 38result ,start = [],0 39for index in range (count ): 40end = start + size + (index < extra ) 41result .append (sorted (cpu for siblings in available [start :end ]for cpu in siblings )) 42start = end 43return result 44 45 46def main ()-> int : 47parser = argparse .ArgumentParser (description = __doc__ ) 48parser .add_argument ("instances" ,type = int ) 49parser .add_argument ("--exclude-pid" ,type = int ,action = "append" ,default = []) 50options = parser .parse_args () 51try : 52reserved :set [int ]= set () 53for pid in options .exclude_pid : 54try : 55reserved .update (os .sched_getaffinity (pid )) 56except ProcessLookupError : 57continue 58groups = partition_cpu_sets (options .instances ,os .sched_getaffinity (0 ),reserved ) 59except (OSError ,ValueError )as error : 60f"CPU affinity: { error } " ,file = sys .stderr ) 61return 1 62for group in groups : 63"," .join (str (cpu )for cpu in group )) 64return 0 65 66 67if __name__ == "__main__" : 68raise SystemExit (main ())